java 动态添加字段 以及 动态新增字段注解

本文是从别的文章作为基础进行创建的,方便自己进行相关操作。

  1. 引入依赖
 <dependency>
     <groupId>javassist</groupId>
     <artifactId>javassist</artifactId>
     <version>3.12.1.GA</version>
 </dependency>
  1. 我这里创建了一个空的对象
public class CitiesVo {
}
  1. 创建一个自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Excel
{
    public String name() default "";
}
  1. 适用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();
        }
    }

亲测有效

  • 4
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值