首页 > 其他 > 详细

自定义注解

时间:2020-05-19 21:14:14      阅读:40      评论:0      收藏:0      [点我收藏+]

自定义注解

1. 元注解

? 元注解:用于修饰注解。

? 四种元注解:

① @Retention: 只能用于修饰一个 Annotation 定义, 用于指定该 Annotation 的生命周期, @Rentention 包含一个 RetentionPolicy 类型的成员变量。

RetentionPolicy.SOURCE:在源文件中有效;
RetentionPolicy.CLASS:在class文件中有效;
RetentionPolicy.RUNTIME:在运行时有效;
@Target: 用于修饰 Annotation 定义, 用于指定被修饰的 Annotation 能用于修饰哪些程序元素。我的理解是可以在哪里使用这个注解。

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    //使用类型的任何语句中
}

③@Documented: 用于指定被该元 Annotation 修饰的 Annotation 类将被javadoc 工具提取成文档。默认情况下,javadoc是不包括注解的。
④@Inherited: 被它修饰的 Annotation 将具有继承性。如果某个类使用了被@Inherited 修饰的 Annotation, 则其子类将自动具有该注解。

2.自定义注解

注解如下:

@Target({ElementType.METHOD,ElementType.TYPE})  //可在方法和类中使用它
@Retention(RetentionPolicy.RUNTIME)  //运行时有效
public @interface MyAnno {

    int value() default 1;
}

使用注解:

@MyAnno(value = 2)
public class Main {

    @MyAnno(value = 2)
    public static void main(String[] args) {

        Class<Main> mainClass = Main.class;
        MyAnno annotation = mainClass.getAnnotation(MyAnno.class);
        int value = annotation.value(); //获取注解的值
        System.out.println(value);
    }
}

运行截图:
技术分享图片

自定义注解

原文:https://www.cnblogs.com/pavi/p/12919385.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!