java反射读取注解

时间:2021-09-15
本文章向大家介绍java反射读取注解,主要包括java反射读取注解使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
  • getAnnotations

  • getAnnotation

  • 以后的框架大量的通过注解读取信息

  • package com.zhou.reflection;
    
    import java.lang.annotation.*;
    import java.lang.reflect.Field;
    
    public class Test07 {
        public static void main(String[] args) throws NoSuchFieldException {
            Class c1 = Comment.class;
            //通过反射获得注解
            Annotation[] annotations = c1.getAnnotations();
            for (Annotation annotation : annotations) {
                System.out.println(annotation);
            }
    
            //通过反射获取value值
            TableZhou annotation = (TableZhou) c1.getAnnotation(TableZhou.class);
            System.out.println(annotation.value());
    
            //获取指定属性的注解
            Field name = c1.getDeclaredField("name");
            FieldZhou annotation1 = name.getAnnotation(FieldZhou.class);
            System.out.println(annotation1.columnName());
            System.out.println(annotation1.length());
            System.out.println(annotation1.type());
    
        }
    }
    
    @TableZhou("db")
    class Comment {
        @FieldZhou(columnName = "db_id", type = "int", length = 10)
        private int id;
        @FieldZhou(columnName = "db_age", type = "int", length = 3)
        private int age;
        @FieldZhou(columnName = "db_name", type = "varchar", length = 5)
        private String name;
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public Comment() {
        }
    
        @Override
        public String toString() {
            return "Comment{" +
                    "id=" + id +
                    ", age=" + age +
                    ", name='" + name + '\'' +
                    '}';
        }
    }
    
    //类注解
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @interface TableZhou {
        String value();
    }
    
    //属性注解
    @Target(ElementType.FIELD)
    @Retention(RetentionPolicy.RUNTIME)
    @interface FieldZhou {
        String columnName();
    
        String type();
    
        int length();
    }
    

原文地址:https://www.cnblogs.com/szZhouFeng/p/15272950.html