Java注解

123 阅读2分钟

「这是我参与2022首次更文挑战的第14天,活动详情查看:2022首次更文挑战

Java注解

今天说一说我们经常用到的java注解,java注解说难吧,也不是很难,说简单吧,我们不经常用的话,对它也就不太熟悉。

看一下自定义一个普通注解的代码:

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LoginClient
{
}

这是自定义的一个注解,注解接口有三个注解,这三个注解是什么含义呢?我们依次看一下

@Target

@Target表示这个注解修饰的对象范围

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
    /**
     * Returns an array of the kinds of elements an annotation type
     * can be applied to.
     * @return an array of the kinds of elements an annotation type
     * can be applied to
     */
    ElementType[] value();
}

有以下范围值,TYPE:作用于类,接口,枚举类,FIELD:作用于域,METHOD:作用于方法,PARAMETER:作用于参数,CONSTRUCTOR:作用于构造器,LOCAL_VARIABLE:作用于局部变量,ANNOTATION_TYPE作用于注解,PACKAGE作用于包,TYPE_PARAMETER作用于普通变量的声明中,TYPE_USE:作用于任何类型的名称。

从以下源码中也可以看到@Target的取值

public enum ElementType {
    /** Class, interface (including annotation type), or enum declaration */
    TYPE,

    /** Field declaration (includes enum constants) */
    FIELD,

    /** Method declaration */
    METHOD,

    /** Formal parameter declaration */
    PARAMETER,

    /** Constructor declaration */
    CONSTRUCTOR,

    /** Local variable declaration */
    LOCAL_VARIABLE,

    /** Annotation type declaration */
    ANNOTATION_TYPE,

    /** Package declaration */
    PACKAGE,

    /**
     * Type parameter declaration
     *
     * @since 1.8
     */
    TYPE_PARAMETER,

    /**
     * Use of a type
     *
     * @since 1.8
     */
    TYPE_USE
}

@Retention

@Retention定义注解保留的级别,RUNTIME表示运行时有效,被编译器记录在类文件中,可以利用反射读取,另外两个CLASS表示被编译器记录在类文件中,但是运行时不会被保留,默认是这一个,SOURCE表示被编译器丢弃,在源文件中保留。

public enum RetentionPolicy {
    /**
     * Annotations are to be discarded by the compiler.
     */
    SOURCE,

    /**
     * Annotations are to be recorded in the class file by the compiler
     * but need not be retained by the VM at run time.  This is the default
     * behavior.
     */
    CLASS,

    /**
     * Annotations are to be recorded in the class file by the compiler and
     * retained by the VM at run time, so they may be read reflectively.
     *
     * @see java.lang.reflect.AnnotatedElement
     */
    RUNTIME
}

@Inherited

@Inherited表表示被标注的类能被继承,注解作用于子类。

@Documented

@Documented表示注解可以被javadoc类工具文档化

总结

这篇文件简单介绍了一下如何自定义一个注解和注解几个标准元注解,@Target表示这个注解修饰的对象范围,@Retention定义注解保留的级别,一般我们使用RUNTIME,这样可以利用反射获取信息,@Documented表示能够被工具文档化,也是用到的。