javaassist动态修改注解

JavaassistAnno ob变量加上了注解A,需要改成B。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package vm;

import vm.anno.A;

public class JavaassistAnno {
@A
private Object ob;
}


public @interface A {
}

public @interface B {
}

直接修改field的属性就可以

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

ClassPool classPool = ClassPool.getDefault();
CtClass ctClass = classPool.getCtClass("vm.JavaassistAnno");
for(CtField ctField : ctClass.getDeclaredFields()){
FieldInfo fieldInfo = ctField.getFieldInfo();
ConstPool cp = fieldInfo.getConstPool();
AnnotationsAttribute att = (AnnotationsAttribute) fieldInfo.getAttribute(AnnotationsAttribute.visibleTag);
AnnotationsAttribute attribute = new AnnotationsAttribute(cp, AnnotationsAttribute.visibleTag);
for (Annotation ann : att.getAnnotations()){
if(ann.getTypeName().equals("vm.anno.A")){
Annotation annotation = new Annotation("vm.anno.B", cp);
attribute.addAnnotation(annotation);
} else {
attribute.addAnnotation(ann);
}
}
fieldInfo.addAttribute(attribute);
}
//这个默认是调用了Thread.currentThread().getContextClassLoader()的defineClass方法,也有api可以指定classloader,或许取到了hibernate的classloader就可以输出过去。
ctClass.toClass();
Class clz = JavaassistAnno.class;
Field field = clz.getDeclaredField("ob");
for (java.lang.annotation.Annotation annotation : field.getAnnotations()){
//可以看到能成功输出@vm.anno.B
System.out.println(annotation);
}