java反射读取注解
package Annotation;
@Annotation
public class TestAnnontation {
@Annotation(a = “sa”,b = 4)
public void test() {
}
}
package Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.FIELD})
public @interface Annotation1_2 {
String columnname();
String type();
String length();
}
package Annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
@Annotation1_1(name = “mzt_student”)
public class TestAnnotation1 {
@Annotation1_2(columnname = “id”,type = “int”,length = “10”)
private int id;
@Annotation1_2(columnname = “studentname”,type = “varchar”,length = “10”)
private String studentname;
@Annotation1_2(columnname = “age”,type = “int”,length = “10”)
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStudentname() {
return studentname;
}
public void setStudentname(String studentname) {
this.studentname = studentname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static void main(String args[]) throws Exception {
Class c = Class.forName("Annotation.TestAnnotation1");
//获取所有有效注解
Annotation[] a = c.getAnnotations();
for(Annotation a1:a) {
System.out.println(a1);
}
//获取类的指定注解
Annotation1_1 a2 = (Annotation1_1) c.getAnnotation( Annotation1_1.class);
System.out.println(a2.name());
//获取类的属性注解
Field f = c.getDeclaredField("id");
Annotation1_2 a3 = f.getAnnotation(Annotation1_2.class);
System.out.println(a3.columnname()+a3.type()+a3.length());
}
}