package cn.notfound945;
import java.lang.annotation.*;
import java.lang.reflect.Field;
public class Main {
public static void main(String[] args) {
Class user = null;
try {
user = Class.forName("cn.notfound945.User");
Annotation[] annotations = user.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
// 获取的注解 value
table annotation = (table)user.getAnnotation(table.class);
System.out.println(annotation.value());
// 获取指定类的注解
Field userDeclaredField = user.getDeclaredField("id");
field annotation1 = userDeclaredField.getAnnotation(field.class);
System.out.println(annotation1.col());
System.out.println(annotation1.type());
System.out.println(annotation1.length());
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 类名的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface table {
String value();
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface field {
String col();
String type();
int length();
}
@table("db_tab")
class User {
@field(col = "db_id", type = "int", length = 10)
private int id;
@field(col = "db_id", type = "varchar", length = 10)
private String name;
@field(col = "db_password", type = "varchar", length = 6)
private String password;
public User(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
}