注解

21 篇文章 0 订阅
0 篇文章 0 订阅

1. 定义

java提供了一种原程序中的元素关联任何信息和任何元数据的途径和方法。(java1.5之后有的)

2. JDK中常见的注解

2.1 @Override

告诉编译器该方法覆盖父类中的方法,用于编译检查。只有在编译前阶段有效

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

2.2 @Deprecated

标记该方法已经过时,但是有可能之前有人用(这个方法不能删除)该注解提醒使用该方法的人不要用这个方法。但是仍然可以用.

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

2.3 @SuppressWarnings()

忽略警告,比如@SuppressWarnings(“deprecated”)表示忽略过时警告

@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {
    /**
     * The set of warnings that are to be suppressed by the compiler in the
     * annotated element.  Duplicate names are permitted.  The second and
     * successive occurrences of a name are ignored.  The presence of
     * unrecognized warning names is <i>not</i> an error: Compilers must
     * ignore any warning names they do not recognize.  They are, however,
     * free to emit a warning if an annotation contains an unrecognized
     * warning name.
     *
     * <p> The string {@code "unchecked"} is used to suppress
     * unchecked warnings. Compiler vendors should document the
     * additional warning names they support in conjunction with this
     * annotation type. They are encouraged to cooperate to ensure
     * that the same names work across multiple compilers.
     * @return the set of warnings to be suppressed
     */
    String[] value();
}

3. 注解的分类

3.1 按照运行机制分

在上面的源码注解中可以看到@Retention(RetentionPolicy.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
}

3.1.1 源码注解

注解只在源码中存在,编译成.class文件时注解就不存在了。

3.1.2 编译时注解

注解在源码和.class文件中都存在注解信息

3.1.3 运行时注解

在运行阶段还存在的注解,可能会影响运行时逻辑。

4. 自定义注解语法

在这里插入图片描述
在这里插入图片描述
不允许map
value那一条是规定
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
接口实现方式不起作用,只能类继承
在这里插入图片描述
在这里插入图片描述

5. 解析注解

通过反射获取类,函数或成员上的运行时注解信息,从而实现动态控制运行时的逻辑。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值