注解(annotation)本質上是一種輔助手段,最常出現在各類框架與工具之中。這些工具會讀取不同的注解資訊,據此採取不同的處理流程,或改變相應程式元素(類別、方法、成員變數等)的行為。JUnit、Struts、Spring 等主流框架無不大量使用注解,讓程式碼的靈活度大幅提升。
下面自訂一個簡單的注解與工具類來實際演示。
Author 注解封裝了作者的年齡與姓名。要特別留意保留策略必須設為 RUNTIME,否則無法透過反射機制取得資訊:
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Author {
long age() default 0L;
String name() default "unknown";
}
在 Bookstore 的某個方法上使用 Author 注解:
public class Bookstore {
@Author(age = 22, name = "benson")
public void setBook() {
}
}
透過反射讀取方法上的注解並印出資訊:
import java.lang.reflect.Method;
public class Tool {
public static void main(String[] args) throws Exception {
Method[] methods = Class.forName(args[0]).getMethods();
for(Method method : methods) {
if(method.isAnnotationPresent(Author.class)) {
Author author = method.getAnnotation(Author.class);
printMessage(author);
}
}
}
private static void printMessage(Author author) {
System.out.printf("Name:%s,Age:%d%n",author.name(),author.age());
}
}
執行 Java 命令時需附上參數「你的包名 + Bookstore」(Eclipse 可在 Run Configuration 裡追加參數)。印出的結果為:
Name:benson,Age:22
整個範例的關鍵在於反射。自 JDK 1.5 起,java.lang.reflect 包新增了 AnnotatedElement 介面(代表可被注解的元素,如類別、方法、欄位、建構子、介面等)。Class、Constructor、Method、Field 等類別都實作了此介面,其宣告如下:
public interface AnnotatedElement {
boolean isAnnotationPresent(Class<? extends Annotation> annotationClass); //判斷該元素是否被指定的元素注解
<T extends Annotation> T getAnnotation(Class<T> annotationClass); //根據給定的注解class返回相應的類
Annotation[] getAnnotations(); //返回指定元素所有的注解,包括繼承下來的。如果沒有則返回零長度的數組
Annotation[] getDeclaredAnnotations(); //同上,只不過不包括繼承的注解
}