Java内置的注解以及自定义一个注解大家都比较熟悉的了,现在来看看注解实现的原理,看看Java的体系下面是如何对注解的支持的。
在讨论前先看一个自定义注解的例子,自定义实现这样一个注解:通过@Test向某类注入一个字符串,通过@TestMethod向某个方法注入一个字符串。
① 创建Test注解,声明作用于类并保留到运行时,默认值为default。
@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)public @interface Test { String value() default "default";}
② 创建TestMethod注解,声明作用于方法并保留到运行时。
@Target({ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)public @interface TestMethod { String value();}
③测试类,运行后输出default和tomcat-method两个字符串,因为@Test没有传入值,所以输出了默认值,而@TestMethod则输出了注入的字符串。
@Test()public class AnnotationTest { @TestMethod("tomcat-method") public void test(){ } public static void main(String[] args){ Test t = AnnotationTest.class.getAnnotation(Test.class); System.out.println(t.value()); TestMethod tm = null; try { tm = AnnotationTest.class.getDeclaredMethod("test