zoukankan      html  css  js  c++  java
  • 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());
        }
    }
    

      

  • 相关阅读:
    几种委托的解释
    Python中的编码风格
    Python的循环
    Python中操作文件
    Python的random模块、string模块、time模块、os模块
    Python中的函数
    Python的数据类型
    使用iview Form 的resetFields()在f12下报错
    滚动条的滚动距离
    编程学习之资源
  • 原文地址:https://www.cnblogs.com/liubaihui/p/10762680.html
Copyright © 2011-2022 走看看