Question

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);
Was it helpful?

Solution

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.

OTHER TIPS

Maybe I am dumb and this is an useless answer but if you are receiving an errors that says

Annotation is abstract; cannot be instantiated

Remember to check the import and make sure that you are importing the right Annotation:

import javassist.bytecode.annotation.Annotation;

And not the wrong library automatically imported by Eclipse that made me waste twenty minutes of my life (java.lang.annotation.Annotation)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top