[jboss-user] [Javassist user questions] - Re: adding annotations

PaulKeeble do-not-reply at jboss.com
Sat Jul 4 21:57:58 EDT 2009


The beauty of a Java agent is it gets passed every loaded class, regardless of classloader. So although you need to filter the list as quickly as possible (you'll get thousands of calls from java.* classes for instance) it is the best way to do the instrumentation.

I have happily got annotation adding working in my code base recently so thought it might help you if I explained roughly how I do it.

First up getting a CtClass:

byte[] byteCode = ....
ClassPool pool = ....
CtClass clazz = pool.makeClass(new ByteArrayInputStream(byteCode)); 


If your using a Java agent it will give you the bytes directly, if you load them yourself in a custom classloader.

Next up you the annotations adding to a CtClass:

CtClass clazz = ....
ClassFile classFile = clazz.getClassFile();
ConstPool cp = classFile.getConstPool();

AnnotationsAttribute attr = new AnnotationsAttribute(cp, AnnotationsAttribute.visibleTag); 

Annotation theAnnotation = new Annotation("org.package.AnnotationType",cp);
annotation.addMemberValue("name", new StringMemberValue("Paul",cp));

attr.setAnnotation(theAnnotation);

clazz.getClassInfo().addAttribute(attr);


That worked well for me as an approach. If you want to see a working version (the far more complicated version based on methods and arrays of values) you can see the latest version of my code at JEMM Git MethodAnnotationTransformation.java



View the original post : http://www.jboss.org/index.html?module=bb&op=viewtopic&p=4241818#4241818

Reply to the post : http://www.jboss.org/index.html?module=bb&op=posting&mode=reply&p=4241818



More information about the jboss-user mailing list