Annotation

1 @Target({ElementType.FIELD, ElementType.METHOD})
2 @Retention(RetentionPolicy.RUNTIME)
3 public @interface Tonny {
4     public int id();
5     public String description() default "nothing"; 
6 }
 1 public class Test {
 2     @Tonny(id = 1)
 3     public int foo;
 4     
 5     @Tonny(id = 2, description = "Hello")
 6     public void bar() {
 7         
 8     }
 9     
10     public static void main(String[] args) throws Exception {
11         Method[] methods = Test.class.getMethods();
12         for(Method method : methods) {
13             boolean hasAnnotation = method.isAnnotationPresent(Tonny.class);
14             if (hasAnnotation) {
15                 Tonny annotation = method.getAnnotation(Tonny.class);
16                 System.out.println("TestAnnotation(mathod="+method.getName()+
17                         ", id="+annotation.id()+", description="+annotation.description()+")");
18             }
19         }
20         
21         Test test = new Test();
22         Field field = test.getClass().getField("foo");
23         Tonny tonny = field.getAnnotation(Tonny.class);
24         field.set(test, tonny.id());
25         System.out.println(test.foo);
26     }
27 } 
  • 使用 @interface 声明一个注解, 方法名即为注解的参数名, 返回值即为参数的类型, 可以使用 default 设置参数的默认值
  • @Retention 用来声明注解的保留策略, 有 CLASS, SOURCE, RUNTIME 三种. 分别表示注解保存在类文件, JVM运行时刻和源代码中. 只有当声明为RUNTIME的时候, 才能够在运行时刻通过反射API来获取到注解的信息.
  • @Target用来声明注解可以被添加在哪些类型的元素上,包括:
    • ElemenetType.CONSTRUCTOR 构造器声明 
    • ElemenetType.FIELD 域声明(包括 enum 实例)
    • ElemenetType.LOCAL_VARIABLE 局部变量声明
    • ElemenetType.METHOD 方法声明
    • ElemenetType.PACKAGE 包声明 
    • ElemenetType.PARAMETER 参数声明 
    • ElemenetType.TYPE 类,接口(包括注解类型)或enum声明

参考:

Java深度历险(六)——Java注解

JAVA 注解示例 详解

图片取自: 

深入理解Java:注解(Annotation)--注解处理器

原文地址:https://www.cnblogs.com/ykt8465279130/p/3238650.html