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


当前回答

Java中的注释提供了一种描述类、字段和方法的方法。本质上,它们是添加到Java源文件中的一种元数据形式,它们不能直接影响程序的语义。但是,注释可以在运行时使用反射读取&这个过程被称为内省。然后,它可以用来修改类、字段或方法。

这个特性,经常被库和sdk (hibernate, JUnit, Spring Framework)利用来简化或减少程序员在使用这些库或sdk时需要做的代码量。因此,可以公平地说,注释和反射在Java中是齐头并进的。

我们还将注释的可用性限制在编译时或运行时。下面是一个创建自定义注释的简单示例

Driver.java

package io.hamzeen;

import java.lang.annotation.Annotation;

public class Driver {

    public static void main(String[] args) {
        Class<TestAlpha> obj = TestAlpha.class;
        if (obj.isAnnotationPresent(IssueInfo.class)) {

            Annotation annotation = obj.getAnnotation(IssueInfo.class);
            IssueInfo testerInfo = (IssueInfo) annotation;

            System.out.printf("%nType: %s", testerInfo.type());
            System.out.printf("%nReporter: %s", testerInfo.reporter());
            System.out.printf("%nCreated On: %s%n%n",
                    testerInfo.created());
        }
    }
}

TestAlpha.java

package io.hamzeen;

import io.hamzeen.IssueInfo;
import io.hamzeen.IssueInfo.Type;

@IssueInfo(type = Type.IMPROVEMENT, reporter = "Hamzeen. H.")
public class TestAlpha {

}

IssueInfo.java

package io.hamzeen;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author Hamzeen. H.
 * @created 10/01/2015
 * 
 * IssueInfo annotation definition
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface IssueInfo {

    public enum Type {
        BUG, IMPROVEMENT, FEATURE
    }

    Type type() default Type.BUG;

    String reporter() default "Vimesh";

    String created() default "10/01/2015";
}

其他回答

注释可以在哪里使用

注释可以应用于声明:类、字段、方法和其他程序元素的声明。在声明上使用时,根据约定,每个注释通常出现在自己的行上。

Java SE 8 Update:注释也可以应用于类型的使用。下面是一些例子:

类实例创建表达式: @Interned MyObject(); 类型转换: myString =(@非空字符串)str; 实现条款: 类UnmodifiableList实现 @Readonly List<@Readonly T>{…} 抛出的异常声明: void monitorTemperature()抛出 @临界温度异常{…}

它通过(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/

注释是添加到Java源文件中的元数据(关于数据的数据)的一种形式。框架主要使用它们来简化客户端代码的集成。下面是我脑海中浮现的几个真实的例子:

JUnit 4 - you add the @Test annotation to each test method you want the JUnit runner to run. There are also additional annotations to do with setting up testing (like @Before and @BeforeClass). All these are processed by the JUnit runner, which runs the tests accordingly. You could say it's an replacement for XML configuration, but annotations are sometimes more powerful (they can use reflection, for example) and also they are closer to the code they are referencing to (the @Test annotation is right before the test method, so the purpose of that method is clear - serves as documentation as well). XML configuration on the other hand can be more complex and can include much more data than annotations can. Terracotta - uses both annotations and XML configuration files. For example, the @Root annotation tells the Terracotta runtime that the annotated field is a root and its memory should be shared between VM instances. The XML configuration file is used to configure the server and tell it which classes to instrument. Google Guice - an example would be the @Inject annotation, which when applied to a constructor makes the Guice runtime look for values for each parameter, based on the defined injectors. The @Inject annotation would be quite hard to replicate using XML configuration files, and its proximity to the constructor it references to is quite useful (imagine having to search to a huge XML file to find all the dependency injections you have set up).

希望我已经让您了解了在不同框架中如何使用注释。

Java中的注释提供了一种描述类、字段和方法的方法。本质上,它们是添加到Java源文件中的一种元数据形式,它们不能直接影响程序的语义。但是,注释可以在运行时使用反射读取&这个过程被称为内省。然后,它可以用来修改类、字段或方法。

这个特性,经常被库和sdk (hibernate, JUnit, Spring Framework)利用来简化或减少程序员在使用这些库或sdk时需要做的代码量。因此,可以公平地说,注释和反射在Java中是齐头并进的。

我们还将注释的可用性限制在编译时或运行时。下面是一个创建自定义注释的简单示例

Driver.java

package io.hamzeen;

import java.lang.annotation.Annotation;

public class Driver {

    public static void main(String[] args) {
        Class<TestAlpha> obj = TestAlpha.class;
        if (obj.isAnnotationPresent(IssueInfo.class)) {

            Annotation annotation = obj.getAnnotation(IssueInfo.class);
            IssueInfo testerInfo = (IssueInfo) annotation;

            System.out.printf("%nType: %s", testerInfo.type());
            System.out.printf("%nReporter: %s", testerInfo.reporter());
            System.out.printf("%nCreated On: %s%n%n",
                    testerInfo.created());
        }
    }
}

TestAlpha.java

package io.hamzeen;

import io.hamzeen.IssueInfo;
import io.hamzeen.IssueInfo.Type;

@IssueInfo(type = Type.IMPROVEMENT, reporter = "Hamzeen. H.")
public class TestAlpha {

}

IssueInfo.java

package io.hamzeen;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author Hamzeen. H.
 * @created 10/01/2015
 * 
 * IssueInfo annotation definition
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface IssueInfo {

    public enum Type {
        BUG, IMPROVEMENT, FEATURE
    }

    Type type() default Type.BUG;

    String reporter() default "Vimesh";

    String created() default "10/01/2015";
}

像Hibernate这样的框架需要大量的配置/映射,大量使用annotation。

看一看Hibernate注解