Java基础(16)——Java注解

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


元注解

作用:负责注解其他注解,Java定义了4个标准的元注解类型 ,用来对其他注解作以说明。如下

@Target

指定当前注解的作用域

1、用法:

// ElementType.METHOD 指定了当前注解是作用在 方法 上的
@Target(ElementType.METHOD)

如图,作用在方法上的自定义注解,放在类上会出现编译错误
在这里插入图片描述
如图,添加了新的作用域
在这里插入图片描述

2、内部实现:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
    
    // 注解的参数  参数类型 + 参数名称 + ()
    ElementType[] value();
}

其中 ElementType 是一个枚举类,枚举值代表作用域 ,实现如下

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

指定当前注解的有效范围

1、用法

@Retention(RetentionPolicy.RUNTIME)

2、内部实现

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

    // 注解的参数  参数类型 + 参数名称 + ()
    RetentionPolicy value();
}

其中 RetentionPolicy 是一个枚举类,枚举值表示 有效范围,如下:

public enum RetentionPolicy {
    /**
     * 有效范围是源码,编译class文件时,注解失效
     * Annotations are to be discarded by the compiler.
     */
    SOURCE,

    /**
     * 有效范围是class文件,在 VM 运行时,注解失效
     * 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,

    /**
     * 有效范围是 VM 运行时
     * 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
}

其中 有效范围大小 RUNTIME>CLASS>SOURCE

@Documented

表示是否将我们的 注解 生成在Java DOC中

@Inherited

表示该注解可以被其他注解继承

自定义注解

@Target(value = {ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation{
    // 注解的参数 = 参数类型 + 参数名称 + ()
    String name() default "hello";
    int id() default 0;
}

注意事项:
1、注解参数可以加默认值
2、注解参数的类型必须为 基本类型、枚举类、String
3、如果注解参数只有一个时,用value命名,好处是使用该注解时直接赋值,不需要写 value = xxx。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值