سؤال

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

هل كانت مفيدة؟

المحلول

setAnnotation takes only one parameter which is of type Annotation, and it erases all the others annotations. If you want to add an annotation to the existing ones, use setAnnotations instead. It takes an array of Annotation so you have first to build the array by gathering all the existing annotations (using getAnnotations) then add the Annotation at the end, then call the method.

a setAnnotation(annotation) call is equivalent to setAnnotations(new Annotation[] { annotation })

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top