天天看點

java反射讀取注解

getAnnotations

getAnnotation

以後的架構大量的通過注解讀取資訊

<code>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(); }</code>