2011-05-17 77 views
2

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

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); 

回答

1

问题解决了,我用的是3.1版本,现在我使用3.12.1.GA(最后的Maven仓库),并在此版本的注释工作。

+0

考虑纪念这一问题作为解决进口;) – Stephan 2011-08-05 12:54:31

1

也许我哑然,这是一个无用的答案,但如果你将收到一个说,一个错误

注释是抽象的;不能被实例化

记住要检查进口,并确保您正在导入正确的注释:

进口javassist.bytecode.annotation.Annotation;

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