本文是从别的文章作为基础进行创建的,方便自己进行相关操作。
- 引入依赖
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
- 我这里创建了一个空的对象
public class CitiesVo {
}
- 创建一个自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Excel
{
public String name() default "";
}
- 适用main方法进行操作
public static void main(String[] args) throws Exception{
//默认的类搜索路径
ClassPool pool = ClassPool.getDefault();
//获取一个ctClass对象 com.example.demo.excel.entity.CitiesVo 这个是包的相对路径
CtClass ctClass = pool.get("com.example.demo.excel.entity.CitiesVo");
try {
//添加age属性
ctClass.addField(CtField.make("private int age;", ctClass));
//添加setAge方法
ctClass.addMethod(CtMethod.make("public void setAge(int age){this.age = age;}", ctClass));
//添加getAge方法
ctClass.addMethod(CtMethod.make("public int getAge(){return this.age;}", ctClass));
//获取这个字段
CtField age = ctClass.getField("age");
FieldInfo fieldInfo = age.getFieldInfo();
ConstPool cp = fieldInfo.getConstPool();
AnnotationsAttribute attribute = (AnnotationsAttribute) fieldInfo.getAttribute(AnnotationsAttribute.visibleTag);
//这里进行了判断 如果说当前字段没有注解的时候 AnnotationsAttribute 这个对象是为空的
//所以要针对这个进行新创建 一个 AnnotationsAttribute 对象
if(ObjectUtils.isEmpty(attribute)){
List<AttributeInfo> attributeInfos =fieldInfo.getAttributes();
attribute = !attributeInfos.isEmpty()?(AnnotationsAttribute) attributeInfos.get(0):
new AnnotationsAttribute(fieldInfo.getConstPool(), AnnotationsAttribute.visibleTag);
}
// Annotation 默认构造方法 typeName:表示的是注解的路径
Annotation bodyAnnot = new Annotation("com.example.demo.excel.annotation.Excel", cp);
// name 表示的是自定义注解的 方法 new StringMemberValue("名字", cp) 表示给name赋值
bodyAnnot.addMemberValue("name", new StringMemberValue("名字", cp));
attribute.addAnnotation(bodyAnnot);
fieldInfo.addAttribute(attribute);
Class aClass1 = ctClass.toClass();
//获取到 新增加的字段
Field cityCode = aClass1.getDeclaredField("age");
//获取 字段上的注解 (这其实可以进行优化 因为有可能 字段上会有多个注解 后续再说)
Excel annotation1 = cityCode.getAnnotation(Excel.class);
String name = annotation1.name();
System.out.println(name);
} catch (Exception e) {
e.printStackTrace();
}
}
亲测有效