问题描述
我们可以使用注解的主要领域有哪些?该功能是否可以替代基于 XML 的配置?
What are the major areas that we can use Annotations? Is the feature a replacement for XML based configuration?
推荐答案
注解是元元对象,可用于描述其他元对象.元对象是类、字段和方法.向对象询问其元对象(例如 anObj.getClass()
)称为 内省.自省可以更进一步,我们可以询问元对象它的注释是什么(例如 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),例如春季 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 中如何以及在哪里使用注解?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!