zoukankan      html  css  js  c++  java
  • java基础篇4之注解

    1 注解的应用(jdk1.5的新特性)

      一个注解相当于一个特殊的类
      例子:
      @SuppressWarning("deprecation")
      @Deprecated
      @Override

      注解相当于一种标记,在程序中加了注解等于为程序打上了某种标记,编译器和工具类通过反射来了解你的类及某种元素
      上有无何种标记,有标记就去干相应的事
      标记可以加在包,类,字段,方法,方法的参数以及局部变量上

    2 注解的定义与反射调用

      注解类
      @interface A{}

      应用了“注解类”的类
      @A
      class B{}

      对“应用了注解类的类”进行反射操作的类
      class C{
        B.class.isAnnotionPresent(A.class);
        A a = B.class.getAnnotion(A.class)
      }

    例子如下:

      //元注解
        @Retention(RetentionPolicy.RUNTIME)
        public @interface itcastAnnotation{}
    
    
        @itcastAnnotation
        public class AnnotationTest{
            if(AnnotationTest.class.isAnnotionPresent(itcastAnnotation.class)){
                itcastAnnotation annotaion =(itcastAnnotation)AnnotationTest.class.getAnnotion(itcastAnnotation.class);
            }
        }

    Annotation保留生命周期
    1、RetentionPolicy.SOURCE (编译器查看)
    2、RetentionPolicy.CLASSS (默认)
    3、RetentionPolicy.RUNTIME (运行时阶段,检查二进制代码)

    @Target(ElementType.METHOD,ElementType.TYPE)
    注解的应用范围

    3 为注解增加各种属性

      @Retention(RetentionPolicy.RUNTIME)
        public @interface itcastAnnotation{
            String color() default "bule";
            String value(); //只有一个属性,则可以省略属性名称
            int[] arrayAttr() default {1,2,3};
            EnumTest.TrafficLamp lamp() default EnumTest.TrafficLamp.RED;
            MetaAnnotation annotationAttr() default @MetaAnnotation("lhm");
        }
    
    
        @itcastAnnotation(annotationAttr=@MetaAnnotation("fix"),color="red",arrayAttr={3,4,5})
        @itcastAnnotation("xyz")
        public class AnnotationTest{
            if(AnnotationTest.class.isAnnotionPresent(itcastAnnotation.class)){
                itcastAnnotation annotaion =(itcastAnnotation)AnnotationTest.class.getAnnotion(itcastAnnotation.class);
                annotaion.color//red    
                annotation.annotationAttr().value();//fix    
            }
        }
    
      public @interface MetaAnnotation {
          String value();
      }
  • 相关阅读:
    Ubuntu配置sublime text 3的c编译环境
    ORA-01078错误举例:SID的大写和小写错误
    linux下多进程的文件拷贝与进程相关的一些基础知识
    ASM(四) 利用Method 组件动态注入方法逻辑
    基于Redis的三种分布式爬虫策略
    Go语言并发编程总结
    POJ2406 Power Strings 【KMP】
    nyoj 会场安排问题
    Server Tomcat v7.0 Server at localhost was unable to start within 45 seconds. If the server requires more time, try increasing the timeout in the server editor.
    Java的String、StringBuffer和StringBuilder的区别
  • 原文地址:https://www.cnblogs.com/atomicbomb/p/6624222.html
Copyright © 2011-2022 走看看