如何以及在哪里在Java中使用批注? [英] How and where are Annotations used in Java?

查看:911
本文介绍了如何以及在哪里在Java中使用批注?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是我们可以使用批注的主要领域?是功能基于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.

这是注释必须跨preTED以这种或那种方式是有用的。注释可通过IDE或编译器,或者在运行时的一个框架在的开发时的PTED间$ P $。

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:


  • 来描述约束或元素的使用:例如, @德precated,@覆盖 @NotNull

  • 来描述元素的自然,例如 @Entity,@TestCase,@WebService

  • 来描述一个元素的行为: @Statefull,@Transaction

  • 来描述如何处理元素: @Column,@XmlElement

  • to describe constraints or usage of an element: e.g. @Deprecated, @Override, or @NotNull
  • to describe the "nature" of an element, e.g. @Entity, @TestCase, @WebService
  • to describe the behavior of an element: @Statefull, @Transaction
  • to describe how to process the element: @Column, @XmlElement

在所有的情况下,注释是用来的描述的元素,并澄清其的的。

In all cases, an annotation is used to describe the element and clarify its meaning.

此前JDK5,信息,现在是需要在其他地方保存批注pssed前$ P $,并经常使用的XML文件。但它是使用注释,因为它们将属于Java的code本身,并因此更容易操作比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的

  • 编辑

  • IDE

  • 测试框架,例如JUnit的

  • IoC容器例如作为春

  • 系列化,例如XML

  • 面向方面编程(AOP),例如Spring AOP的

  • 应用程序服务器,例如EJB容器,Web服务

  • 对象 - 关系映射(ORM),如休眠,JPA

  • 还有更多...

...不得不在项目龙目岛,它使用注解来定义如何生成等于散code 方法。

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

这篇关于如何以及在哪里在Java中使用批注?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆