javaassist动态修改注解 Posted on 2019-02-11 | In programming | JavaassistAnno ob变量加上了注解A,需要改成B。 123456789101112131415package vm;import vm.anno.A;public class JavaassistAnno { @A private Object ob;}public @interface A {}public @interface B {} 直接修改field的属性就可以1234567891011121314151617181920212223242526ClassPool 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);}