Java 中如何以及在何处使用注解?

2022-01-13 00:00:00 annotations java

我们可以使用注解的主要领域有哪些?该功能是否可以替代基于 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 的例子,它使用注释来定义如何生成 equalshashCode 方法.

...have a look for instance at the project Lombok, which uses annotations to define how to generate equals or hashCode methods.

相关文章