通过反射使用注解
要让注解有作用,最简单的方式是通过反射使用注解。
第一步:创建注解类
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyAnnotation {
String value() default "";
}
第二步:使用注解
@MyAnnotation("Hello")
public class TestClass {
}
第三步:编写方法
public static void test(Object o) {
Class<?> clazz = o.getClass();
MyAnnotation anno = clazz.getAnnotation(MyAnnotation.class);
if (anno != null) {
System.out.println(anno.value());
} else {
System.out.println(o);
}
}
第四步:测试
public static void main(String[] args) {
test(new TestClass());
}