zoukankan      html  css  js  c++  java
  • 自定义注解

    自定义注解

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

    运行截图:

    作者:pavi

    出处:http://www.cnblogs.com/pavi/

    本文版权归作者和博客园所有,欢迎转载。转载请在留言板处留言给我,且在文章标明原文链接,谢谢!

    如果您觉得本篇博文对您有所收获,觉得我还算用心,请点击右下角的 [推荐],谢谢!

  • 相关阅读:
    [转] EJB 3和Spring技术体系比较
    JBOSS只能本机localhost和127.0.0.1能访问的解决
    JBOSS EAP 6.0+ Standalone模式安装成Windows服务
    IBM WebSphere MQ 7.5基本用法
    maven学习(上)- 基本入门用法
    mac下环境变量、maven3.1.1 及 jdk1.7.0.45配置
    java:读/写配置文件
    java:使用匿名类直接new接口
    java与c#的反射性能比较
    XmlSpy / XSD 以及 验证
  • 原文地址:https://www.cnblogs.com/pavi/p/12919385.html
Copyright © 2011-2022 走看看