I’m trying to add some annotations to classes while they are loaded.
For that I’ve wrote a java agent transformer which gets the class bytecode upon loading and can change it.
When I run the following code the new annotation apears on the class but all previous annotation and fields / methods are removed.
CtClass ctClass = classPool.makeClass(new java.io.ByteArrayInputStream(classFileBuffer));
ClassFile classFile = clazz.getClassFile();
ConstPool constPool = classFile.getConstPool();
AnnotationsAttribute attr= new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
javassist.bytecode.annotation.Annotation annotation = new javassist.bytecode.annotation.Annotation(type, constPool);
attr.setAnnotation(annotation);
classFile.addAttribute(attr);
classFileBuffer = ctClass.toBytecode();
Where classFileBuffer is the byte array which is returned to the class loader.
If anyone has an idea why the previous class annotations and code are removed it will be very helpful.
Thanks,
Avner
setAnnotationtakes only one parameter which is of typeAnnotation, and it erases all the others annotations. If you want to add an annotation to the existing ones, usesetAnnotationsinstead. It takes an array ofAnnotationso you have first to build the array by gathering all the existing annotations (usinggetAnnotations) then add theAnnotationat the end, then call the method.a
setAnnotation(annotation)call is equivalent tosetAnnotations(new Annotation[] { annotation })