Java注解

@Target

  • @Target(ElementType.TYPE) //接口、类、枚举、注解
  • @Target(ElementType.FIELD) //字段、枚举的常量
  • @Target(ElementType.METHOD) //方法
  • @Target(ElementType.PARAMETER) //方法参数
  • @Target(ElementType.CONSTRUCTOR) //构造函数
  • @Target(ElementType.LOCAL_VARIABLE)//局部变量
  • @Target(ElementType.ANNOTATION_TYPE)//注解
  • @Target(ElementType.package) ///包 这里可以使用多个,比如:@Target({ElementType.TYPE,ElementType.METHOD})

@Retention

Retention(保留)注解说明,这种类型的注解会被保留到那个阶段. 有三个值:

  • RetentionPolicy.SOURCE —— 这种类型的Annotations只在源代码级别保留,编译时就会被忽略
  • RetentionPolicy.CLASS —— 这种类型的Annotations编译时被保留,在class文件中存在,但JVM将会忽略
  • RetentionPolicy.RUNTIME —— 这种类型的Annotations将被JVM保留,所以他们能在运行时被JVM或其他使用反射机制的代码所读取和使用.
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.SOURCE)
public @interface SourceRetention {
    String value() default "";
}
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.CLASS)
public @interface ClassRetention {
    String value() default "";
}
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface RuntimeRetention {
    String value() default "";
}

Test类

import org.junit.Test;

@SourceRetention
public class SourceRetentionTest{
    @Test
    public void testValue() {
        SourceRetention a = SourceRetentionTest.class.getAnnotation(SourceRetention.class);
        System.out.println(a.value());
    }
}

import org.junit.Test;

@ClassRetention
public class ClassRetentionTest{

    @Test
    public void testValue() {
        ClassRetention a = ClassRetentionTest.class.getAnnotation(ClassRetention.class);
        System.out.println(a.value());
    }
}

import org.junit.Test;

@RuntimeRetention(value = "RuntimeRetentionTest")
public class RuntimeRetentionTest{

    @Test
    public void testValue() {
        RuntimeRetention a = RuntimeRetentionTest.class.getAnnotation(RuntimeRetention.class);
        System.out.println(a.value());
    }
}

 

 

 

@Documented

Documented 注解表明这个注解应该被 javadoc工具记录. 默认情况下,javadoc是不包括注解的. 但如果声明注解时指定了 @Documented,则它会被 javadoc 之类的工具处理, 所以注解类型信息也会被包括在生成的文档中.

 

 

注解类都继承与Annotation,和普通接口的区别,不可以实现多继承。

 

posted @ 2017-04-27 15:02  图生  阅读(153)  评论(0)    收藏  举报