Java注解笔记

2017-05-16  本文已影响0人  hbh404

Java注解详解

Java注解是JDK1.5以后添加的特性,自定义注解需要声明为@interface

最简单的注解:

public @interface Demo {
}   

定义注解时需要一些元注解

@Target 参数表示在什么地方使用该注解,一个方法或一个域等

CONSTRUCTOR: 构造器申明
FIELD: 域申明
LOCAL_VARIABLE: 局部变量申明
METHOD: 方法申明
PACKAGE: 包申明
PARAMETER: 参数申明
TYPE: 类,接口或枚举申明

源码:

@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();
}

@Retention 用来定义该注解是哪一个级别可用:在源代码中、类文件中、还是运行时
没有注解元素的注解称为标记注解

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

源码:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
    /**
     * Returns the retention policy.
     * @return the retention policy
     */
    RetentionPolicy value();
}

@Documented 表示将此注解包含在javadoc中

源码:

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

@Inherited 表示允许子类继承父类中的注解

源码:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Inherited {
}

注解元素可以使用所有的基本类型、String、Class、Annotation等使用其他的类型会报错。

上一篇 下一篇

猜你喜欢

热点阅读