2

我正在使用 javassist 创建一个类并为其添加注释。当我使用 CtClass.writeFile 并且看到带有 Java 反编译器的类文件时,注释就在那里,但是当我使用 class.getAnnotations() 或 class.getDeclaredAnnotations() 时,列表为空。

ClassPool pool = ClassPool.getDefault();
pool.insertClassPath(new ClassClassPath(cl.loadClass("javax.jws.WebService")));
CtClass pikoClass = pool.makeClass("br.com.stuff.Piko");
ConstPool constPool = pikoClass.getClassFile().getConstPool();
AnnotationsAttribute attr = new AnnotationsAttribute(constPool, annotationsAttribute.visibleTag);
Annotation annoWebService = Annotation(constPool, pool.get("javax.jws.WebService"));
attr.setAnnotation(annoWebService);
pikoClass.getClassFile().addAttribute(attr);
Class piko = pikoClass.toClass();
piko.getDeclaredAnnotations(); // this is always empty
// Also tried
Annotation annoWebService = new Annotation("WebService", constPool);
Annotation annoWebService = new Annotation("@WebService", constPool);
Annotation annoWebService = new Annotation("javax.jwsWebService", constPool);
Annotation annoWebService = new Annotation("@javax.jwsWebService", constPool);
4

2 回答 2

2

问题解决了,我使用的是 3.1 版,现在我使用的是 3.12.1.GA(最后在 maven 存储库上),并且在这个版本上注释有效。

于 2011-05-18T18:30:45.253 回答
1

也许我很愚蠢,这是一个无用的答案,但如果你收到一个错误,上面写着

注解是抽象的;无法实例化

请记住检查导入并确保您正在导入正确的注释:

导入 javassist.bytecode.annotation.Annotation;

而不是 Eclipse 自动导入的错误库让我浪费了 20 分钟的生命(java.lang.annotation.Annotation

于 2016-06-15T07:35:20.750 回答