java注解-特殊语法

概述

本文通过 java内置注解 理解注解的原理 和 使用

源代码

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

@Override 源代码

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

@Deprecated 源代码

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

特殊语法1

如果注解 只有一个属性,且命名为 value,
那么在使用注解的时候可以直接使用:@注解名(注解值)
其等效于:@注解名(value = 注解值)

注意: 如果需要给2个属性传参,就不能省略 value ,必须写全

例子

如上面源代码中的:@Retention(RetentionPolicy.RUNTIME)

特殊语法2

如果注解中的某个属性返回 数组类型,在使用时又出现只需要填入一个值的情况,
那么在使用注解时可以直接写为:@注解名(类型名 = 类型值),
其等效于:@注解名(类型名 = {类型值})

例子

如 @Override 源代码:

@Target(ElementType.METHOD)

如 @Deprecated 源代码:

@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})

感谢:
https://blog.csdn.net/xsp_happyboy/article/details/80987484