通过反射获取注解
以及获取注解的value值
以及注解的属性
import java.lang.annotation.*;
import java.lang.reflect.Field;
public class Test16 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class c1 = Class.forName("com.test.reflection.Student2");
//通过反射获取注解
Annotation[] annotations = c1.getAnnotations(); //获取c1的注解
for (Annotation annotation : annotations) {
System.out.println(annotation); //遍历输出
}
//通过反射获取类注解的value值
Student2.Tablehe tablehe = (Student2.Tablehe)c1.getAnnotation(Student2.Tablehe.class);
System.out.println(tablehe.value());
// 通过反射获取指定的注解,例如获取类属性
Field f = c1.getDeclaredField("id"); //获取“name”属性
Student2.Fieldhe annotation = f.getAnnotation(Student2.Fieldhe.class); //得到注解所属的类
System.out.println(annotation.columnName()); //输出属性注解的value
System.out.println(annotation.type());
System.out.println(annotation.length());
}
}
@Student2.Tablehe("db_student") //数据库表的注解
class Student2{
@Fieldhe(columnName = "db_age",type = "int",length = 10) //输入定义的三个值
private int age;
@Fieldhe(columnName = "db_name",type = "String",length = 20)
private String name;
@Fieldhe(columnName = "db_int",type = "int",length = 10)
private int id;
// 类名的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Tablehe{
String value();
}
// 属性的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Fieldhe{
//定义了三个值
String columnName();
String type();
int length();
}
// 定义类的无参构造器
public Student2() {
}
// 定义类的有参构造器
public Student2(int age, String name, int id) {
this.age = age;
this.name = name;
this.id = id;
}
@Override
public java.lang.String toString() {
return "Student2{" +
"age=" + age +
", name=" + name +
", 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 int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}