Understanding Annotations in Java

最常见的annotation

    @Override:用在方法之上,用来告诉别人这一个方法是改写父类的
    @Deprecated:建议别人不要使用旧的API的时候用的,编译的时候会用产生警告信息,可以设定在程序里的所有的元素上.
    @SuppressWarnings:暂时把一些警告信息消息关闭
    @Entity:表示该类是可持久化的类

@Target里面的ElementType是用来指定Annotation类型可以用在哪些元素上的.例如:
       TYPE(类型)、FIELD(属性)、METHOD(方法)、PARAMETER(参数)、CONSTRUCTOR(构造函数)、LOCAL_VARIABLE(局部变量),、PACKAGE(包),其中的TYPE(类型)是指可以用在Class,Interface,Enum和Annotation类型上。

  RetentionPolicy 共有三种策略,分别为:

    SOURCE:这个Annotation类型的信息只会保留在程序源码里,源码如果经过了编译之后,Annotation的数据就会消失,并不会保留在编译好的.class文件里面
    CLASS:这个Annotation类型的信息保留在程序源码里,同时也会保留在编译好的.class文件里面,在执行的时候,并不会把这些信息加载到JVM中。注:默认策略为CLASS类型
    RUNTIME:表示在源码、编译好的.class文件中保留信息,在执行的时候会把这一些信息加载到JVM中去的


    访问权只能用public和默认(default)修饰
    参数成员只能用基本类型byte,short,char,int,long,float,double,boolean八种基本数据类型和String,Enum,Class,annotations等数据类型,以及这一些类型的数组



Understanding Annotations in Java
Introduction

This article discusses the way of creating annotations in Java. It also shows how to apply annotations to other declarations. Finally it discusses how to obtain annotation information at runtime using Reflection.
Background

Annotation is a new feature introduced by J2SE 5 that allows programmers to embed additional information called metadata into a Java source file. Annotations do not alter the execution of a program but the information embedded using annotations can be used by various tools during development and deployment.
Using the code

Creating an annotation is similar to creating an interface. But the annotation declaration is preceded by an @ symbol. The annotation declaration itself is annotated with the @Retention annotation. The @Retention annotation is used to specify the retention policy, which can be SOURCE, CLASS, or RUNTIME.

    RetentionPolicy.SOURCE retains an annotation only in the source file and discards it during compilation.
    RetentionPolicy.CLASS stores the annotation in the .class file but does not make it available during runtime.
    RetentionPolicy.RUNTIME stores the annotation in the .class file and also makes it available during runtime.


// Specifying runtime retention policy
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation
{
    String author();    // Annotation member
    String date();      // Annotation member
}

An annotation cannot have the extends clause. However, annotations implicitly extend the Annotation interface. The body of an annotation consists of method declarations without body. These methods work like fields.

In the above example, I have created two members, author and date to represent information about the creator, and date of writing of the class and method.

Once an annotation is created, it can be applied to classes, methods, fields, parameters, enums, and so on. While applying an annotation to a declaration, you must provide values for its members as follows:


// Applying annotation to the class
@MyAnnotation(author="Azim",date="22/10/2011,23/10/2011")
public class Test
{
    // Applying annotation to the method
    @MyAnnotation(author="Azim",date="22/10/2011")
    public static void testMethod()
    {
        System.out.println("Welcome to Java");
        System.out.println("This is an example of Annotations");
    }
    public static void main(String args[])
    {
        testMethod();
        showAnnotations();
    }

Annotations can be queried at runtime using Reflection as follows:

public static void showAnnotations()
// Function to show annotation information
{
    Test test=new Test(); // Instantiating Test class
    try
    {
        Class c=test.getClass(); // Getting Class reference
        Method m=c.getMethod("testMethod"); // Getting Method reference
        // Getting Class annotation
        MyAnnotation annotation1=
          (MyAnnotation)c.getAnnotation(MyAnnotation.class);
        // Getting Method annotation
        MyAnnotation annotation2=m.getAnnotation(MyAnnotation.class);
        // Displaying annotation information
        System.out.println("Author of the class: "+annotation1.author());
        // Displaying annotation information
        System.out.println("Date of Writing the class: "+annotation1.date());
        // Displaying annotation information
        System.out.println("Author of the method: "+annotation2.author());
        // Displaying annotation information
        System.out.println("Date of Writing the method: "+annotation2.date());
    }
    catch(NoSuchMethodException ex)
    {
        System.out.println("Invalid Method..."+ex.getMessage());
    }
}

In the above code, I have queried annotations applied to the class Test as well as the method testMethod().

To obtain annotation information for the class, the following statement is used:

MyAnnotation annotation1=(MyAnnotation)c.getAnnotation(MyAnnotation.class);

To obtain annotation information for the method, the following statement is used:

MyAnnotation annotation2=m.getAnnotation(MyAnnotation.class);

The annotation information is printed by using annotation objects.
Points of interest

The Java program is compiled on the command line as follows:

javac Test.java

and executed as follows:

java Test

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

I am a trainer by profession. Currently I am working with NIIT (Mumbai, India) as a Senior Faculty. I enjoy programming as a hobby. My favorite technologies are Flash, Flex and Silverlight.

Of late I have developed keen interest in WPF and Windows Mobile programming.

Apart from computers, my favorite pastime is bicycling.

猜你喜欢

转载自zgq456.iteye.com/blog/1938159