Annotation 注解

Annotation分为两种,第一种为系统内置注解,第二种为自定义注解。

系统内置注解:例如@Override,@Dprecated

自定义注解:定义格式为 

【public】 @interface Annotation名称{

    数据类型 变量名称();

}

其中数据类型和变量自定义,不作限制。

Retention和RetentionPolicy

在Annotation中,可以使用Retention定义个Annotation的保存范围,此Annotation的定义如下:

@Retention(RetentionPolicy.RUNTIME)  
@Target(ElementType.FIELD)  
public @interface Meaning {  
    FormItemType value() ;  //设置为枚举类型  
}

RetentionPolicy表示保存范围,主要有



ElementType表示使用类型,主要有



想要注解变得有意义,需要结合反射使用。

例:

package com.itmyhome;  
  
import java.lang.annotation.Annotation;  
import java.lang.reflect.Method;  
  
class Demo{  
    @SuppressWarnings("unchecked")  
    @Deprecated  
    @Override  
    public String toString(){  
        return "hello";  
    }  
}  
  
public class T {  
    public static void main(String[] args) throws Exception{  
        Class<?> c = Class.forName("com.itmyhome.Demo");  
        Method mt = c.getMethod("toString");   //找到toString方法  
        Annotation an[] = mt.getAnnotations(); //取得全部的Annotation  
        for(Annotation a:an){  
            System.out.println(a);  
        }  
          
    }  
}


原文地址:https://www.cnblogs.com/timeboy/p/9464403.html