反射机制获取一个类的注解:
先定义一个注解,并设置为可以被反射:
package homework01;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
// 让这个注解可反射到
@Retention(value = RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
int id();
String name();
}
再定义一个类,用注解标注:
package homework01;
@MyAnnotation(id = 1001, name = "张三")
public class User {
}
测试代码:
package homework01;
public class Test01 {
public static void main(String[] args) throws Exception {
// 先反射获取一个类
Class theClass = Class.forName("homework01.User");
System.out.println(theClass.getSimpleName()); // User
// 判断类前面是否有指定注解
boolean hasAnn = theClass.isAnnotationPresent(MyAnnotation.class);
System.out.println(hasAnn); // true
if (hasAnn) {
// 获取该注解对象
MyAnnotation myAnn = (MyAnnotation)theClass.getAnnotation(MyAnnotation.class);
// 获取属性值
int id = myAnn.id();
String name = myAnn.name();
System.out.println(id + " " + name); // 1001 张三
}
}
}
同样也可以使用类似的方法反射到方法,甚至变量前面的注解!