問題描述
我們可以使用注解的主要領域有哪些?該功能是否可以替代基于 XML 的配置?
What are the major areas that we can use Annotations? Is the feature a replacement for XML based configuration?
推薦答案
注解是meta-meta-objects,可以用來描述其他meta-objects.元對象是類、字段和方法.向對象詢問其元對象(例如 anObj.getClass()
)稱為 introspection.內省可以更進一步,我們可以詢問元對象它的注釋是什么(例如 aClass.getAnnotations
).自省和注釋屬于所謂的反射和元編程.
Annotations are meta-meta-objects which can be used to describe other meta-objects. Meta-objects are classes, fields and methods. Asking an object for its meta-object (e.g. anObj.getClass()
) is called introspection. The introspection can go further and we can ask a meta-object what are its annotations (e.g. aClass.getAnnotations
). Introspection and annotations belong to what is called reflection and meta-programming.
注釋需要以一種或另一種方式解釋才能有用.IDE 或編譯器可以在開發時 或由框架在運行時 解釋注釋.
An annotation needs to be interpreted in one way or another to be useful. Annotations can be interpreted at development-time by the IDE or the compiler, or at run-time by a framework.
注解處理是一種非常強大的機制,可以以多種不同的方式使用:
Annotation processing is a very powerful mechanism and can be used in a lot of different ways:
- 描述元素的約束或使用:例如
@Deprecated、@Override
或@NotNull
- 描述元素的性質",例如
@Entity、@TestCase、@WebService
- 描述一個元素的行為:
@Statefull, @Transaction
- 描述如何處理元素:
@Column, @XmlElement
在所有情況下,注釋都用于描述元素并闡明其含義.
In all cases, an annotation is used to describe the element and clarify its meaning.
在 JDK5 之前,現在用注釋表示的信息需要存儲在其他地方,并且經常使用 XML 文件.但是使用注解更方便,因為它們屬于 Java 代碼本身,因此比 XML 更容易操作.
Prior to JDK5, information that is now expressed with annotations needed to be stored somewhere else, and XML files were frequently used. But it is more convenient to use annotations because they will belong to the Java code itself, and are hence much easier to manipulate than XML.
注解的使用:
- 文檔,例如XDoclet
- 編譯
- 集成開發環境
- 測試框架,例如JUnit
- IoC 容器,例如作為春天
- 序列化,例如XML
- 面向方面的編程 (AOP),例如Spring AOP
- 應用服務器,例如EJB 容器、Web 服務
- 對象關系映射 (ORM),例如休眠,JPA
- 還有更多...
...看看項目 Lombok 的例子,它使用注釋來定義如何生成 equals
或 hashCode
方法.
...have a look for instance at the project Lombok, which uses annotations to define how to generate equals
or hashCode
methods.
這篇關于Java 中如何以及在何處使用注解?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!