JAVA元注解的使用

版权声明:没有版权,转载署名即可,有事联系我邮箱[email protected],其他消息我收不到。 https://blog.csdn.net/u010414666/article/details/81543216

java自定义注解时需要用到几个基本注解,成为“元注解”

元注解有四个:

@Retention 
@Target
@Document 
@Inherited 

@Retention:注解的保留位置

@Retention(RetentionPolicy.SOURCE)   //注解仅存在于源码中,在class字节码文件中不包含
@Retention(RetentionPolicy.CLASS)     // 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,
@Retention(RetentionPolicy.RUNTIME)  // 注解会在class字节码文件中存在,在运行时可以通过反射获取到

@Target:注解的作用目标

    @Target(ElementType.TYPE)   //用于接口、类、枚举、注解 ①
    @Target(ElementType.FIELD)  //字段、枚举的常量 ②
    @Target(ElementType.METHOD)  //方法 ③
    @Target(ElementType.PARAMETER)  //方法参数 ④
    @Target(ElementType.CONSTRUCTOR)  //构造函数 ⑤
    @Target(ElementType.LOCAL_VARIABLE)  //局部变量 ⑥
    @Target(ElementType.ANNOTATION_TYPE)  //用于注解类,类似ElementType.TYPE ⑦
    @Target(ElementType.PACKAGE) ///包   ⑧
    @Target(ElementType.TYPE_PARAMETER)   //键入参数声明(since 1.8) ⑨
    @Target(ElementType.TYPE_USE)   //使用类型   (since 1.8) ⑩

    当允许注解在多处使用时:
    @Target({ElementType.PARAMETER,ElementType.METHOD})

各注解样例

@TypeAnnotation //ElementType.TYPE ①
public class TestAnnotation {

    @FieldAnnotation //ElementType.FIELD ②
    private String field;

    @ConstructorAnnotation //ElementType.CONSTRUCTOR ⑤
    public TestAnnotation() {

    }

    @MethodAnnotation //ElementType.METHOD  ③
    public String testMethod(@ParameterAnnotation String parameter, //ElementType.PARAMETER ④
                             String anotherParameter) {
        @LocalVariableAnnotation String localVariable; //ElementType.LOCAL_VARIABLE ⑥
        return parameter;
    }
}

另外几个相比于上面几个有点特殊

/**
 * ElementType.PACKAGE定义的注解只能用于 package-info.java 
 * 详见:https://blog.csdn.net/achuo/article/details/50610559
 */
@PackageAnnotation //ElementType.PACKAGE  ⑧
package neo.tao; 

import neo.tao.annotation.PackageAnnotation;
/**
 * ElementType.ANNOTATION_TYPE 在定义注解时用于注解类上
 * /
@AnnotationTypeAnnotation  //ElementType.ANNOTATION_TYPE  ⑦
@TypeAnnotation
public @interface TestAnnotationTypeAnnotation {

}

还剩两个是jdk 1.8之后加入的,自己没有尝试过,就不照搬百度介绍了,可自行学习

@Document:说明该注解将被包含在javadoc中

@Inherited:说明子类可以继承父类中的该注解

猜你喜欢

转载自blog.csdn.net/u010414666/article/details/81543216