[英]Javassist set annotation to superclass field
How to set annotation to superclass field ? 如何将注释设置为超类字段? For the code i have i see only the annotation is set to
domain
but not to name
field which belongs to superclass when i do ctClass.toClass()
对于我拥有的代码,当我执行
ctClass.toClass()
时,我仅看到注释设置为domain
而不是属于超类的name
字段
class A {
private String name;
}
Class B extends A {
private String domain;
}
getFields(ctClass).forEach(f -> {
final AnnotationsAttribute attr = new AnnotationsAttribute(cpool, AnnotationsAttribute.visibleTag);
final Annotation annot = new Annotation(Indexed.class.getName(), cpool);
attr.addAnnotation(annot);
f.getFieldInfo().addAttribute(attr);
});
List<CtField> getFields(CtClass ctClass) throws NotFoundException {
final List<CtField> fields = new LinkedList<CtField>();
fields.addAll(Arrays.asList(ctClass.getDeclaredFields()));
while (ctClass.getSuperclass() != null) {
ctClass = ctClass.getSuperclass();
fields.addAll(Arrays.asList(ctClass.getDeclaredFields()));
}
return fields;
}
You need to use the constant pool table of the class declaring the method. 您需要使用声明该方法的类的常量池表。 Also you should use the
getAttribute(..)
to obtain the annotations attribute, if you create a new one, the current annotations are erased. 另外,您应该使用
getAttribute(..)
获取注释属性,如果创建一个新属性,则会删除当前注释。
The for each can execute something similar to: 每个可以执行类似于以下内容的操作:
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);
});
Note: you should be careful with the classes that you modify, if one of the classes extends a java class that has a field defined this will fail. 注意:如果您修改的类之一扩展了定义了字段的java类,则该类将失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.