使用Javassist向运行时生成的方法/类添加注释
我正在使用Javassist生成类foo
,使用方法bar
,但我似乎无法找到一种方法来向方法添加注释(注释本身不是运行时生成的)。 我试过的代码看起来像这样:
ClassPool pool = ClassPool.getDefault(); // create the class CtClass cc = pool.makeClass("foo"); // create the method CtMethod mthd = CtNewMethod.make("public Integer getInteger() { return null; }", cc); cc.addMethod(mthd); ClassFile ccFile = cc.getClassFile(); ConstPool constpool = ccFile.getConstPool(); // create the annotation AnnotationsAttribute attr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag); Annotation annot = new Annotation("MyAnnotation", constpool); annot.addMemberValue("value", new IntegerMemberValue(ccFile.getConstPool(), 0)); attr.addAnnotation(annot); ccFile.addAttribute(attr); // generate the class clazz = cc.toClass(); // length is zero java.lang.annotation.Annotation[] annots = clazz.getAnnotations();
显然我做错了,因为annots
是一个空数组。
这是注释的样子:
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface MyAnnotation { int value(); }
最终解决了它,我把注释添加到了错误的地方。 我想将它添加到方法中,但我将它添加到类中。
这是固定代码的样子:
// wrong ccFile.addAttribute(attr); // right mthd.getMethodInfo().addAttribute(attr);
- @PersistenceUnit注释不会创建EntityManageFactory emf = null
- 上下文:annotation-config是@AutoWired的替代品吗?
- 在Stanford CoreNLP中添加新的注释器
- 使用注释确保不会丢弃方法返回的值
- 使用AnnotationProcessor构建Maven,解析src / main / java中的文件,并生成源代码到generate-test-sources / test-annotations
- 如何根据条件禁用TestNG测试
- 如何使用hibernate JPA注释映射嵌套集合Map <Key,List >?
- JSF 2使用@ManagedProperty注入Spring bean / service而没有xml
- JUnit :(可能是间接的)将自己包含在SuiteClass中