自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface Test{
public int id();
public String description() default "no description";
}
@Documented的目的就是让这一个Annotation类型的信息能够显示在javaAPI说明文档上,
@Inherited需要把Annotation的数据继承给子类
@Target里面的ElementType是用来指定Annotation类型可以用在哪一些元素上的
@Retention设置为RUNTIME表示在源码、编译好的.class文件中保留信息,在执行的时候会把这一些信息加载到JVM中去的.
下面是一个使用注解和解析注解的实例
package Test_annotation;
import java.lang.reflect.Method;
public class Test_1 {
@Test(id =1,description="hello method_1")
public void method_1() {
}
@Test(id = 2)
public void method_2() {
}
@Test(id=3,description="last method")
public void method_3() {
}
public static void main(String[] args) {
Method[] methods = Test_1.class.getDeclaredMethods();
for (Method method : methods) {
boolean hasAnnotation = method.isAnnotationPresent(Test.class);
if (hasAnnotation) {
Test annotation = method.getAnnotation(Test.class);
System.out.println("Test( method = " + method.getName()
+ " , id = " + annotation.id() + " , description = "
+ annotation.description() + " )");
}
}
}
}
输出结果如下:
Test( method = method_1 , id = 1 , description = hello method_1 )
Test( method = method_2 , id = 2 , description = no description )
Test( method = method_3 , id = 3 , description = last method )