我们可以使用注释的主要领域是什么?该特性是基于XML的配置的替代品吗?


当前回答

Java EE 5倾向于使用注释而不是XML配置。例如,在EJB3中,EJB方法上的事务属性是使用注释指定的。他们甚至使用注释将pojo标记为ejb,并将特定的方法指定为生命周期方法,而不需要接口的实现。

其他回答

它通过(a)编译器检查或(b)代码分析附加有关代码的其他信息

**

以下是内置注释::2类型

**

类型1)应用于java代码的注释:

@Override // gives error if signature is wrong while overriding.
Public boolean equals (Object Obj) 

@Deprecated // indicates the deprecated method
Public doSomething()....

@SuppressWarnings() // stops the warnings from printing while compiling.
SuppressWarnings({"unchecked","fallthrough"})

类型2)应用于其他注释的注释:

@Retention - Specifies how the marked annotation is stored—Whether in code only, compiled into the class, or available at run-time through reflection.

@Documented - Marks another annotation for inclusion in the documentation.

@Target - Marks another annotation to restrict what kind of java elements the annotation may be applied to

@Inherited - Marks another annotation to be inherited to subclasses of annotated class (by default annotations are not inherited to subclasses).

**

自定义注解::

** http://en.wikipedia.org/wiki/Java_annotation#Custom_annotations


为了更好地理解,请尝试下面的链接:用例子详细说明


http://www.javabeat.net/2007/08/annotations-in-java-5-0/

它对于注释类非常有用,无论是在方法、类或字段级别,都是关于类的一些与类不太相关的东西。

您可以有自己的注释,用于将某些类标记为仅测试使用。它可能只是为了文档的目的,或者您可以在编译产品候选发行版时通过过滤它来强制执行它。

你可以使用注释来存储一些元数据,就像在插件框架中一样,例如插件的名称。

它只是另一种工具,它有很多用途。

它是基于XML的替代品吗 配置吗?

不完全如此,但是与代码结构紧密对应的配置(例如JPA映射或Spring中的依赖注入)通常可以用注释代替,这样通常就不那么冗长、烦人和痛苦了。几乎所有著名的框架都进行了这种转换,尽管旧的XML配置通常仍然是一种选项。

注释有两个视图

在用户视图中,大多数时候,注释就像一个快捷键,为你节省一些按键,或使你的程序更具可读性 从供应商的角度来看,处理器对注释的看法更像是一个轻量级的“接口”,你的程序确实要面对一些东西,但没有显式地“实现”特定的接口(这里也就是注释)。

例如,在jpa中,您可以定义如下内容

@Entity class Foo {...}

而不是

class Foo implements Entity {...}

两者都说了同样的话"Foo是一个实体类"

Java EE 5倾向于使用注释而不是XML配置。例如,在EJB3中,EJB方法上的事务属性是使用注释指定的。他们甚至使用注释将pojo标记为ejb,并将特定的方法指定为生命周期方法,而不需要接口的实现。