java注解简介

来源:互联网 发布:c语言顺序栈的实现 编辑:程序博客网 时间:2024/05/18 02:49

注解简单的理解成在代码中加注额外信息的一种手段,这些信息可以再稍后的某个时刻使用,使用时与反射配合。主要用来:

  • 生成文档
  • 跟踪代码依赖
  • 编译时检查

从分类上看来,java定义了三类注解:

  • jdk内置的系统注解,编译时检查(@Override,@Deprecated,@SuppressWarnings)
  • 元注解,专职负责注解其他注解(@Target,@Retention,@Documented,@Inherited)
  • 自定义注解

一般说来,注解存在于一个单独的.java文件中,会被编译成.class文件。

系统内置注解

@Override用来编译时检查方法覆盖父类方法,只能修饰方法。查看@Override的实现可以看到:

@Target(ElementType.METHOD)@Retention(RetentionPolicy.SOURCE)public @interface Override { }

@Override注解被两个元注解修饰,@Target和@Retention。这两个注解分别表示@Override这个注解修饰的是方法,并且只保留在源码级别,编译时将被编译器丢弃。

@Deprecated用来提示这个部分已经不推荐使用,已经过时

@Documented@Retention(RetentionPolicy.RUNTIME)@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})public @interface Deprecated { }

从代码可以看出,不推荐使用的部分可以使类,接口,构造器,域声明,局部变量,方法声明,参数声明。VM在运行期间也保留注解。@Documented说明这个注解包含在javadoc中。

@SuppressWarnings关闭编译器不当的警告信息

@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})@Retention(RetentionPolicy.SOURCE)public @interface SuppressWarnings {        String[] value();}

定义体里面的 String[] value(); 是注解元素,可以想象成变量。使用时需要为@SuppressWarnings的value指定值。例如:

@SuppressWarnings(value={ "deprecation", "unchecked" })

表示关闭过时警告和未检查的类型转换警告

元注解

@Target 表示该注解使用范围,可能的ElementType参数包括:

  • CONSTRUCTOR:构造器的声明
  • FIELD:域声明(包括enum实例)
  • LOCAL_VARIABLE:局部变量声明
  • METHOD:方法声明
  • PACKAGE:包生明
  • PARAMETER:参数声明
  • TYPE:类,接口(包括注解类型)或enum类型

@Retention 表示注解的保留级别,可能的RetentionPolicy参数包括:

  • SOURCE:注解将被编译器丢弃
  • CLASS:注解在class文件中可用,但会被VM丢弃
  • RUNTIME:VM将在运行期也保留注解,因此可以通过反射机制读取注解里的信息

@Documented 将注解包含在javadoc中
@Inherited 允许子类继承父类中的注解

自定义注解

定义方式很像,例如:

@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface Test{    public int id();    public String description() default "no description";}

id是int类型的注解元素,description是String类型的注解元素,默认值”no description”。没有设定默认值的注解元素需要在使用时显示赋值,就像@SuppressWarnings一样。因为保留类型是RUNTIME,所以能够在程序运行期间拿到。例如:

class TT {    @Test(id = 0)    public void annot0() { System.out.println("runtime annotation test"); }    @Test(id = 1, description = "just for fun")    public void annot1() { }}public class App{    public static void main( String[] args )    {        Class<?> cl = TT.class;        for(Method m : cl.getDeclaredMethods()) {            Test t = m.getAnnotation(Test.class);            if(t != null) {                System.out.println("Found Annotation Test: id="+t.id()                        +" descripition="+t.description());            }        }    }}

输出:
Found Annotation Test: id=0 descripition=no description
Found Annotation Test: id=1 descripition=just for fun
注解元素可以包含的类型有:

  • 所有基本类型(int,float,boolean等)
  • String
  • Class
  • enum
  • Annotation
  • 以上类型的数组

通过自定义注解,并编写出街处理器,可以在运行时利用注解干很多有意思的事情。

2 0
原创粉丝点击