天天看点

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>