概述
通过Class在运行时获取注解信息
示例
MyAnnotation
package com.ycy2;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation1 {
public String name();
public int age() default 20;
}
MyClass
package com.ycy2;
@MyAnnotation1(name = "ljx",age = 18)
//@MyAnnotation1(name = "ljx")
public class MyClass {
}
测试类
package com.ycy2;
public class Test01 {
public static void main(String[] args) throws Exception {
testAnnotation1();
}
public static void testAnnotation1() throws Exception {
Class<?> clazz = Class.forName("com.ycy2.MyClass");
// 判断注解是否存在
boolean isPresent = clazz.isAnnotationPresent(MyAnnotation1.class);
if (isPresent) {
// 获取注解
MyAnnotation1 annotation = clazz.getAnnotation(MyAnnotation1.class);
// 获取注解中的属性值
String name = annotation.name();
int age = annotation.age();
System.out.println("name = " + name);
System.out.println("age = " + age);
}
}
}
结果: