2011-05-17 55 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