import cn.afterturn.easypoi.excel.annotation.Excel;
import io.swagger.annotations.ApiModelProperty;
public class Animal {
@ApiModelProperty(value = "年龄", position = 3)
// @Export(name = "年龄", order = 1, width = 20)
@Excel(name = "年龄", orderNum = "1")
public String age;
}
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;
import javassist.NotFoundException;
import javassist.bytecode.*;
import javassist.bytecode.annotation.Annotation;
import javassist.bytecode.annotation.StringMemberValue;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws NotFoundException {
ClassPool pool = ClassPool.getDefault();
CtClass ct = pool.get("Animal");
CtField cf = ct.getField("age");
FieldInfo fieldInfo = cf.getFieldInfo();
System.out.println("属性名称: " + cf.getName());
System.out.println("***********************************");
AnnotationsAttribute attribute = (AnnotationsAttribute) fieldInfo.getAttribute(AnnotationsAttribute.visibleTag);
ConstPool cp = fieldInfo.getConstPool();
Annotation annotation = new Annotation("Export(name=\"年龄\", order=1, width=20)", cp);
attribute.addAnnotation(annotation);
System.out.println(attribute);
Annotation[] annotations = attribute.getAnnotations();
System.out.println(Arrays.toString(annotations));
System.out.println(annotation);
System.out.println("***********************************");
ConstPool cp = fieldInfo.getConstPool();
AnnotationsAttribute attribute2 = new AnnotationsAttribute(cp, AnnotationsAttribute.visibleTag);
System.out.println(attribute2);
// Annotation annotation = new Annotation("Export", cp);
System.out.println(annotation);
annotation.addMemberValue("unitName", new StringMemberValue("basic-entity", cp));
attribute2.setAnnotation(annotation);
Annotation annotation2 = attribute2.getAnnotation("Export");
String text = ((StringMemberValue) annotation2.getMemberValue("unitName")).getValue();
System.out.println("修改后的注解名称==:" + text);
AnnotationsAttribute annotationsAttribute = new AnnotationsAttribute(cp, AnnotationsAttribute.visibleTag);
System.out.println(annotationsAttribute.getAnnotation("io.swagger.annotations.ApiModelProperty"));
System.out.println(annotationsAttribute);
}
}
/**
* 功能,动态的给类属性添加注解
*
* @param className 类名
* @param attributeName 类属性
* @param typeName 注解类型
*/
public static void addAnnotation(String className, String attributeName, String typeName) {
try {
ClassPool pool = ClassPool.getDefault();
CtClass ct = pool.get(className);
CtField cf = ct.getField(attributeName);
FieldInfo fieldInfo = cf.getFieldInfo();
AnnotationsAttribute attribute = (AnnotationsAttribute) fieldInfo.getAttribute(AnnotationsAttribute.visibleTag);
ConstPool cp = fieldInfo.getConstPool();
Annotation annotation = new Annotation(typeName, cp);
System.out.println(annotation);
attribute.addAnnotation(annotation);
System.out.println(Arrays.toString(attribute.getAnnotations()));
} catch (NotFoundException e) {
log.error("此类不存在", e);
}
}