getAnnotations
getAnnotation
public class reflection {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class c1 =Class.forName("reflection");
//通过反射获得注解
Annotation[] annotations = c1.getAnnotations();
System.out.println(annotations);
for (Annotation s : annotations) {
System.out.println(s);
}
TableKuang tableKuang =(TableKuang)c1.getAnnotation(TableKuang.class);
String value =tableKuang.value();
System.out.println(value);
//获得类指定的注解
Field f =c1.getDeclaredField("id");
Fieldkuange annotation =f.getAnnotation(Fieldkuange.class);
System.out.println(annotation.columnName());
System.out.println(annotation.type());
System.out.println(annotation.length());
}
}
@TableKuang("db_student")
class Student2{
@Fieldkuange(columnName ="db_id",type="int",length = 10)
private int id;
@Fieldkuange(columnName ="db_age",type="int",length = 10)
private int age;
@Fieldkuange(columnName ="db_name",type="varchar",length = 3)
private String name;
public Student2(){
}
public Student2(int id, int age, String name) {
this.id = id;
this.age = age;
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;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student2{" +
"id=" + id +
", age=" + age +
", name=‘" + name + ‘\‘‘ +
‘}‘;
}
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableKuang{
String value();
}
//属性的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Fieldkuange{
String columnName();
String type();
int length();
}
原文:https://www.cnblogs.com/small-hao/p/14142117.html