Java注解简单介绍

来源:互联网 发布:北斗tv有网络电视版吗 编辑:程序博客网 时间:2024/06/10 20:43

什么是注解?

注解就是某种注解类型的一个实例,我们可以用它在某个类上进行标注,这样编译器在编译我们的文件时,会根据我们自己设定的方法来编译类。

在自定义注解之前,我们要先了解一下Java为我们提供的元注解(注解自定义的注解)。

一、元注解:

元注解的作用就是负责注解其他注解。Java5.0定义了4个标准的meta-annotation类型,它们被用来提供对其它 annotation类型作说明。Java5.0定义的元注解:

  1.@Target

  2.@Retention

  3.@Documented

       4.@Inherited

这些类型和它们所支持的类在java.lang.annotation包中可以找到。

1)@Target

@Target说明了Annotation所修饰的对象范围:Annotation可被用于 packages、types(类、接口、枚举、Annotation类型)、类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch参数)。在Annotation类型的声明中使用了target可更加明晰其修饰的目标。

取值(ElementType)有:

1. ElementType .CONSTRUCTOR:用于描述构造器

2. ElementType .FIELD:用于描述域

3. ElementType .LOCAL_VARIABLE:用于描述局部变量

4. ElementType .METHOD:用于描述方法

5. ElementType .PACKAGE:用于描述包

6. ElementType .PARAMETER:用于描述参数

7.TYPE:用于描述类、接口(包括注解类型) 或enum声明

2)@Retention

@Retention定义了该Annotation被保留的时间长短:某些Annotation仅出现在源代码中,而被编译器丢弃;而另一些却被编译在class文件中;编译在class文件中的Annotation可能会被虚拟机忽略,而另一些在class被装载时将被读取(请注意并不影响class的执行,因为Annotation与class在使用上是被分离的)。使用这个meta-Annotation可以对 Annotation的“生命周期”限制。

取值(RetentionPoicy)有:

1. RetentionPoicy .SOURCE:在源文件中有效(即源文件保留)

2. RetentionPoicy .CLASS:在class文件中有效(即class保留)

3. RetentionPoicy .RUNTIME:在运行时有效(即运行时保留)

3)@Documented

@Documented用于描述其它类型的annotation应该被作为被标注的程序成员的公共API,因此可以被例如javadoc此类的工具文档化。Documented是一个标记注解,没有成员。

4)@Inherited

@Inherited 元注解是一个标记注解,@Inherited阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。

二、自定义注解

如下代码,声明一个接口,并为其添加注解:

package com.java.annotation;

import java.lang.annotation.Documented;

import java.lang.annotation.Retention;

importjava.lang.annotation.RetentionPolicy;

@Documented

@Retention(RetentionPolicy.RUNTIME)

public @interface Animal {

         String name();

         String address();

}

下面测试上边声明的接口:

package com.java.annotation;

@Animal(name="monkey",address="非洲")

public class TestAnnotation {

         publicstatic void print(Class clazz){

                   Animal animal = (Animal) clazz.getAnnotation(Animal.class);

                   if(animal != null) {

                            System.out.println("name:"+animal.name()+",address:"+animal.address());

                   }else{

                            System.out.println("animalerror!");

                   }

         }

         publicstatic void main(String[] args) {

                   TestAnnotation.print(TestAnnotation.class);

         }

}

结果输出:


0 0
原创粉丝点击