• java自定义注解教程


    1、定义注解类

    @Documented
    @Inherited
    @Target({ElementType.FIELD,ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface IniterValue {
        public String value() default "";
    }
    

     2、定义使用注解的类

    @Data
    public class User {
        @IniterValue(value = "2")
        private Integer age;
        @IniterValue(value = "小明")
        private String name;
    }
    

     3、定义注解解析器

    public class UserFactory {
        public static <T> T create(Class<T> t) throws IllegalAccessException, InstantiationException {
            T t1 = t.newInstance();
            Field[] fields = t1.getClass().getDeclaredFields();
            for (Field field:fields) {
                if(field.isAnnotationPresent(IniterValue.class)){
                    IniterValue annotation = field.getAnnotation(IniterValue.class);
                    try {
                        field.setAccessible(true);
                        Class<?> type = field.getType();
                        Object obj=null;
                        if(type == Integer.class){
                            obj = Integer.valueOf(annotation.value());
    
                        }
                        if(type==String.class){
                            obj=annotation.value();
                        }
                        field.set(t1,obj);
    
                       // method.invoke(t1,annotation.value(),annotation.intValue());
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
            return t1;
    
        }
    }
    

     4、测试

    public class Test {
        public static void main(String[] args) throws InstantiationException, IllegalAccessException {
            User user = UserFactory.create(User.class);
            System.out.println(user.getAge());
        }
    }
    

      

  • 相关阅读:
    数据结构课后
    idea 使用java 链接sqlservice 2008
    超链接 a href 提交表单通过post方式
    课程主页之课程接口
    课程主页之课程表数据
    课程表分析
    课程前端简单页面
    前台的登录注册
    ORM常用字段及参数与查询 -刘
    Celery配置与使用
  • 原文地址:https://www.cnblogs.com/liubaihui/p/10762680.html
Copyright © 2020-2023  润新知