点击查看代码
package com.kuang.reflection;
// 练习反射操作注解
import java.lang.annotation.*;
import java.lang.reflect.Field;
public class Test12 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class c1 = Class.forName("com.kuang.reflection.Student2");
// 通过反射获得注解
Annotation[] annotations = c1.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
// 获得注解value的值
Tablekuang tablekuang= (Tablekuang)c1.getAnnotation(Tablekuang.class);
String value = tablekuang.value();
System.out.println(value);
// 获得指定注解
Field f = c1.getDeclaredField("name"); // 一个属性
Fieldkuang annotation = f.getAnnotation(Fieldkuang.class); // 获得属性注解
System.out.println(annotation.columnNam());
System.out.println(annotation.type());
System.out.println(annotation.length());
}
}
@Tablekuang("db_student")
class Student2{
@Fieldkuang(columnNam = "db_name",type = "varchar",length = 3)
private String name;
@Fieldkuang(columnNam = "db_id", type = "int", length = 10)
private int id;
@Fieldkuang(columnNam = "db_age", type = "int", length = 3)
private int age;
public Student2() {
}
public Student2(String name, int id, int age) {
this.name = name;
this.id = id;
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;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student2{" +
"name='" + name + '\'' +
", id=" + id +
", age=" + age +
'}';
}
}
// 类名的注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Tablekuang{
String value();
}
// 属性的注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface Fieldkuang{
String columnNam();
String type();
int length();
}