譯 Programming with typesafe enums and annotations in Java 5

原文爲:

Java 101: The next generation: The essential Java language features tour, Part 2

   Programming with typesafe enums and annotations in Java 5


Annotations——Java註解

 

你可能會遇到這種需求:通過與元數據(描述其他數據的數據)關聯來註解你Java應用程序。一直以來,Java通過transient關鍵字提供了一種即時註解(ad hoc annotation)機制,這允許你標識一個成員變量在序列化過程中應該被忽略。但是,直到java5才正式地引入了一種標準方式去註解程序。


Java5平臺提供了下面四種註解機制:

1. 聲明註解類型:@interface;

2. 元註解類型:可以識別應用於註解類型的程序元素和註解的生命週期(註解類型的一個實例)等;

3.通過Java反射API的一種擴展方式來支持註解處理,你可以用來發現一個程序的運行時註解,並引入一個泛型Annotation處理工具(APT);

4. 標準的註解類型;


我將通過下面的實例解釋如何運用這些方式並闡明註解的難點。


Annotations

You’veprobably encountered the need to annotate elements of your Java applicationsbyassociating metadata (data that describes other data) with them.Java has always provided an ad hoc annotation mechanism via the transientreserved word, which lets you annotate fields that are to be excluded duringserialization. But it didn’t offer a standard way to annotate program elementsuntil Java 5.

Java5’s general annotation mechanism consists of four components:

1.An @interface mechanism for declaring annotation types.
2. Meta-annotation types, which you can use to identify the applicationelements to which an annotation type applies; to identify the lifetime of anannotation (an instance of an annotation type); and more.
3. Support for annotation processing via an extension to the Java ReflectionAPI, which you can use to discover a program’s runtime annotations, and theintroduction of a generalized tool for processing annotations.
4. Standard annotation types.

I’ll explain how to use these componentsand point out some of the challenges of annotations in the examples thatfollow.

 



持續更新中。。。









發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章