我嘗試使用了Javassist生成我的實體類。一切進展順利,直到我添加到ID字段的GeneratedValue註釋。 @Id註釋工作正常,但是當我添加@GeneeratedValue時,我得到一個異常。這是我的代碼:了Javassist annoations問題
ClassPool cp = ClassPool.getDefault();
CtClass ctClass = cp.makeClass("test.Snake");
ClassFile classFile = ctClass.getClassFile();
classFile.setVersionToJava5();
AnnotationsAttribute attribute = new AnnotationsAttribute(classFile.getConstPool(), AnnotationsAttribute.visibleTag);
Annotation idAnnotation = new Annotation(classFile.getConstPool(), ClassPool.getDefault().get("javax.persistence.Id"));
attribute.addAnnotation(idAnnotation);
Annotation gvAnnotation = new Annotation(classFile.getConstPool(), ClassPool.getDefault().get("javax.persistence.GeneratedValue"));
attribute.addAnnotation(gvAnnotation);
CtField idField = new CtField(ClassPool.getDefault().get("java.lang.Long"), "id", ctClass);
idField.getFieldInfo().addAttribute(attribute);
ctClass.addField(idField);
CtField nameField = new CtField(ClassPool.getDefault().get("java.lang.String"), "name", ctClass);
ctClass.addField(nameField);
AnnotationsAttribute attr = new AnnotationsAttribute(classFile.getConstPool(), AnnotationsAttribute.visibleTag);
Annotation annotation = new Annotation(classFile.getConstPool(), ClassPool.getDefault().get("javax.persistence.Entity"));
attr.addAnnotation(annotation);
classFile.addAttribute(attr);
snakeClass = ctClass.toClass();
newInstance = snakeClass.newInstance();
這是個例外,我得到:
java.lang.NullPointerException
at javassist.bytecode.ConstPool.getUtf8Info(ConstPool.java:565)
at javassist.bytecode.annotation.EnumMemberValue.getValue(EnumMemberValue.java:98)
at javassist.bytecode.annotation.EnumMemberValue.write(EnumMemberValue.java:116)
at javassist.bytecode.annotation.Annotation.write(Annotation.java:316)
at javassist.bytecode.AnnotationsAttribute.setAnnotations(AnnotationsAttribute.java:246)
at javassist.bytecode.AnnotationsAttribute.addAnnotation(AnnotationsAttribute.java:211)
at ClassLoadingTest.javassitTest(ClassLoadingTest.java:56)
這似乎是一個@GeneratedValue問題。當我單獨使用它時,我也會得到這個異常。當我使用Eclipse調試器來觀看變量的值,我得到得到這個
com.sun.jdi.InvocationException occurred invoking method.
,而不是註釋值。但是對於Id註解,它顯示了一個javassist註釋對象。
我是新來了Javassist。誰能幫我?
其實我找到了解決方案。我在玩Annotations的構造函數,以及將類名稱作爲字符串的函數,然後constPool正常工作!雖然我不知道爲什麼! 註釋gvAnnotation =新的註釋( 「javax.persistence.GeneratedValue」,classFile.getConstPool()); – Wickoo 2010-06-12 16:55:46