Javassist将注释设置为超类字段

时间:2018-03-17 00:17:12

标签: java java-8 bytecode javassist

如何将注释设置为超类字段?对于我所看到的代码,我看到只有注释设置为domain而不是属于超级类的name字段{i} {/ 1}

ctClass.toClass()

1 个答案:

答案 0 :(得分:0)

您需要使用声明该方法的类的常量池表。此外,您应该使用getAttribute(..)来获取注释属性,如果您创建一个新注释属性,则会删除当前注释。

每个人都可以执行类似于:

的操作
fieldsByClass.forEach(ctField -> {
    CtClass ctClass = ctField.getDeclaringClass();
    ClassFile classFile = ctClass.getClassFile();
    ConstPool constPool = classFile.getConstPool();
    FieldInfo fieldInfo = ctField.getFieldInfo();
    AnnotationsAttribute annotationsAttribute = (AnnotationsAttribute) fieldInfo
            .getAttribute(AnnotationsAttribute.visibleTag);
    Annotation annotation = new Annotation(Deprecated.class.getName(), constPool);
    annotationsAttribute.addAnnotation(annotation);
    ctField.getFieldInfo().addAttribute(annotationsAttribute);
});

注意:您应该小心修改的类,如果其中一个类扩展了一个定义了字段的java类,那么这将失败。

相关问题