歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Annotation的應用場合

Annotation的應用場合

日期:2017/3/1 10:00:58   编辑:Linux編程

annotation一般作為一種輔助途徑,應用在軟件框架或工具中,在這些工具類中根據不同的 annontation注解信息采取不同的處理過程或改變相應程序元素(類、方法及成員變量等)的行為。

例如:Junit、Struts、Spring等流行工具框架中均廣泛使用了annontion。使代碼的靈活性大提高。

下面自定義一個簡單的注解和工具類來演示。

Author注解封裝了作者的年齡和姓名。(保持策略需設置為RUNTIME,否則無法通過反射機制獲取信息)

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Author {

long age() default 0L;
String name() default "unknown";
}

書店類:該類某個方法用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

這裡的核心是用到了Java反射機制。在JDK1.5版本以後,java.lang.reflect包裡新增了AnnotatedElement(被注解的元素,即類,方法,字段,構造函數,接口等)。像Class,Constructor,Method,Filed等類都實現了AnnotatedElement接口。該接口的聲明如下:

public interface AnnotatedElement {

boolean isAnnotationPresent(Class<? extends Annotation> annotationClass); //判斷該元素是否被指定的元素注解


<T extends Annotation> T getAnnotation(Class<T> annotationClass); //根據給定的注解class返回相應的類


Annotation[] getAnnotations(); //返回指定元素所有的注解,包括繼承下來的。如果沒有則返回零長度的數組

Annotation[] getDeclaredAnnotations(); //同上,只不過不包括繼承的注解
}

Copyright © Linux教程網 All Rights Reserved