什么是注解
注解(Annotation) 提供了一種安全的類似注釋的機(jī)制辩稽,為我們在代碼中添加信息提供了一種形式化得方法废境,使我們可以在稍后某個時刻方便的使用這些數(shù)據(jù)(通過解析注解來使用這些 數(shù)據(jù))耽梅,用來將任何的信息或者元數(shù)據(jù)與程序元素(類挨约、方法、成員變量等)進(jìn)行關(guān)聯(lián)儒飒。其實就是更加直觀更加明了的說明谬莹,這些說明信息與程序業(yè)務(wù)邏輯沒有關(guān) 系,并且是供指定的工具或框架使用的桩了。Annotation像一種修飾符一樣附帽,應(yīng)用于包、類型井誉、構(gòu)造方法蕉扮、方法、成員變量颗圣、參數(shù)及本地變量的申明語句中喳钟。
Annotation其實是一種接口。通過java的反射機(jī)制相關(guān)的API來訪問Annotation信息在岂。相關(guān)類(框架或工具中的類)根據(jù)這些信息來決定如何使用該程序元素或改變它們的行為奔则。Java語言解釋器在工作時會忽略這些Annotation,因此在JVM中這些Annotation是“不起作用”的洁段,只能通過配套的工具才能對這些Annotation類型的信息進(jìn)行訪問和處理应狱。
Java SE5內(nèi)置了三種標(biāo)準(zhǔn)注解
- @Override,表示當(dāng)前的方法定義將覆蓋超類中的方法祠丝。
- @Deprecated疾呻,使用了注解為它的元素編譯器將發(fā)出警告除嘹,因為注解 @Deprecated是不贊成使用的代碼,被棄用的代碼岸蜗。
- @SuppressWarnings尉咕,關(guān)閉不當(dāng)編譯器警告信息。
Java提供了4中注解璃岳,專門負(fù)責(zé)新注解的創(chuàng)建
- @Documented –注解是否將包含在JavaDoc中
- @Retention –什么時候使用該注解
- @Target –注解用于什么地方
-
@Inherited – 是否允許子類繼承該注解
image.png
定義注解的方式
注解的可用的類型包括以下幾種:所有基本類型年缎、String、Class铃慷、enum单芜、Annotation、以上類型的數(shù)組形式犁柜。元素不能有不確定的值洲鸠,即要么有默認(rèn)值,要么在使用注解的時候提供元素的值馋缅。而且元素不能使用null作為默認(rèn)值扒腕。注解在只有一個元素且該元素的名稱是value的情況下,在使用注解的時候可以省略“value=”萤悴,直接寫需要的值即可瘾腰。
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UseCase {
public String id();
public String description() default "no description";
}
使用注解
public class PasswordUtils {
@UseCase(id = 47, description = "Passwords must contain at least one numeric")
public boolean validatePassword(String password) {
return (password.matches("\\w*\\d\\w*"));
}
@UseCase(id = 48)
public String encryptPassword(String password) {
return new StringBuilder(password).reverse().toString();
}
}
注解處理器
public static void main(String[] args) {
List<Integer> useCases = new ArrayList<Integer>();
Collections.addAll(useCases, 47, 48, 49, 50);
trackUseCases(useCases, PasswordUtils.class);
}
//方法注解
public static void trackUseCases(List<Integer> useCases, Class<?> cl) {
for (Method m : cl.getDeclaredMethods()) {
UseCase uc = m.getAnnotation(UseCase.class);
if (uc != null) {
System.out.println("Found Use Case:" + uc.id() + " "
+ uc.description());
useCases.remove(new Integer(uc.id()));
}
}
for (int i : useCases) {
System.out.println("Warning: Missing use case-" + i);
}
}
//字段注解
public static String getFiledComment(Object obj, String fieldName) {
Field[] fields =obj.getClass().getDeclaredFields();
String filedComment = "";
for (Field field : fields) {
if (fieldName.equals(field.getName())) {
FieldComment fieldCommentAnnotation = field.getAnnotation(FieldComment.class);
filedComment = fieldCommentAnnotation.desc();
break;
}
}
return filedComment;
}