Javassist - 向类添加注释不适用于反射
我正在使用 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);
I'm creating a class using javassist and add annotation to it. When I use CtClass.writeFile and I see class file with Java decompiler the annotation is there but when I use class.getAnnotations() or class.getDeclaredAnnotations() the list is empty.
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题解决了,我使用的是 3.1 版本,现在我使用的是 3.12.1.GA(最后在 maven 存储库上)并且在此版本上注释有效。
Problem solved, I was using version 3.1, now I'm using 3.12.1.GA (last on maven repository) and on this version annotations works.
也许我很愚蠢,这是一个无用的答案,但如果你收到一个错误,说
请记住检查导入并确保导入正确的注释:
并不是 Eclipse 自动导入的错误库让我浪费了二十分钟的时间 (java.lang.annotation.Annotation)
Maybe I am dumb and this is an useless answer but if you are receiving an errors that says
Remember to check the import and make sure that you are importing the right Annotation:
And not the wrong library automatically imported by Eclipse that made me waste twenty minutes of my life (java.lang.annotation.Annotation)