zoukankan      html  css  js  c++  java
  • 注解

    注解的定义:

    public @interface TestAnnotation {    
    }

    元注解:

    对注解进行注解的注解,可以应用到注解上

    // 设置注解的保留期
    //@Retention(RetentionPolicy.RUNTIME)  注解可以保留到运行期间  会被加载到jvm中去
    //@Retention(RetentionPolicy.CLASS)  注解可以保留到编译进行的时候,不会被加载到jvm中去
    @Retention(RetentionPolicy.SOURCE)   //注解只会保留在源码中
    public @interface TestAnnotation {    
    }
    //将注解中的元素包含到 Javadoc 中去。
    @Documented
    public @interface TestAnnotation {    
    }
    //定义了注解可以应用的地方
    //@Target(ElementType.ANNOTATION_TYPE) //可以给注解添加注解
    //@Target(ElementType.CONSTRUCTOR) //可以给构造函数添加注解
    //@Target(ElementType.FIELD) //可以给字段属性添加注解
    //@Target(ElementType.LOCAL_VARIABLE) //可以给局部变量添加属性
    //@Target(ElementType.METHOD) //可以给方法添加属性
    //@Target(ElementType.PACKAGE) //可以给包添加注解
    //@Target(ElementType.PARAMETER) //可以给参数添加注解
    @Target(ElementType.TYPE) //可以给类型添加注解,比如类型,枚举,接口
    public @interface TestAnnotation {    
    }

    @Inherited

    Inherited 是继承的意思,但是它并不是说注解本身可以继承,而是说如果一个超类被 @Inherited 注解过的注解进行注解的话,

    那么如果它的子类没有被任何注解应用的话,那么这个子类就继承了超类的注解。

    注解的属性

    注解的属性也叫做成员变量。注解只有成员变量,没有方法。注解的成员变量在注解的定义中以“无形参的方法”形式来声明,

    其方法名定义了该成员变量的名字,其返回值定义了该成员变量的类型。

    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface TestAnnotation {    
        int id();
        String msg();
    }
    
    public class Test1 {
        @TestAnnotation(id=1,msg="123")
        private void method1() {    
        }
    }

     注解与反射

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface TestAnnotation {    
        int id();
        String msg();
    }
    
    @TestAnnotation(id=1,msg="123")
    public class Test1 {
        public static void main(String[] args) {    
            // 判断是否应用了某个注解
            boolean hasAnnotation=Test1.class.isAnnotationPresent(TestAnnotation.class);
            System.out.println(hasAnnotation);
            
            if(hasAnnotation){
                //获取注解
                TestAnnotation testAnnotation=Test1.class.getAnnotation(TestAnnotation.class);
                
                System.out.println(testAnnotation.id()); //获取注解中的属性
                System.out.println(testAnnotation.msg());
            }
        }    
    }

    注解的应用

    注解的基本语法,创建如同接口,但是多了个 @ 符号。注解主要给编译器及工具类型的软件用的。

    注解的提取需要借助于 Java 的反射技术,反射比较慢,所以注解使用时也需要谨慎计较时间成本。

    参考:http://www.importnew.com/23564.html

              https://www.cnblogs.com/xdp-gacl/p/3622275.html

    https://blog.csdn.net/briblue/article/details/73824058/

  • 相关阅读:
    这个站不错
    Using YQL as crawler for Javascript
    xmldatabase domdatabase
    语法分析器自动生成工具一览
    Ruby, Concurrency, and You
    图书影印
    数据可视化我在寻找一款类似vfp或是access这样自带可视化风格的数据库或是键盘数据库
    金融工程
    joke
    在ubuntu上安装全文搜索中文分词Coreseek/sphinx及和Rails集成 转载
  • 原文地址:https://www.cnblogs.com/yanliang12138/p/10329846.html
Copyright © 2011-2022 走看看