1. 程式人生 > 其它 >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();
    }