注解

来源:互联网 发布:java字符串补零 编辑:程序博客网 时间:2024/05/19 06:47

        注解(Annotation)相当于一种标记,在程序中加了注解就等于为程序打上了某种标记,没打则等于没有标记。以后javac编译器,开发工具和其他程序可以用反射来了解你的类及各种元素上有我何种标记,看你有什么标记就去干相应的事。注解可以加在包、类、字段、方法、方法的参数及局部变量上。

       java提供的几个基本注解:

       @SuppressWarnings   压缩警告

       @Deprecated              过时

       @Override                  重载

       注解就相当于一个特殊的类,程序中的每一个注解都是一个注解类实例对象

       自定义一个注解:

       @Retention(RetentionPolicy.RUNTIME)//元注解:注解作用时段

       @Target({ElementType.METHOD,ElementType.TYPE}//注解作用范围

        public @interface NewAnnotatioType{

            String color()  default "blue";//注解属性,默认值为blue   

        }  

        注解属性可为各种类型的属性 

        通过反射获得注解对象:

        @NewAnnotetionType(color = "red")

         public   class  Main
         {

               public static void main(String[]args)

                {

                   if( Main.class.isAnnotationPresent(NewAnnotationType.class))//判断是否含有NewAnnotationType注解

                   {
                       NewAnnotationType newAnnotation =(NewAnnotationType)Main.class.getAnnotation 

(NewAnnotationType.class);//获取含有的注解
                        System.out.println(newAnnotation);
                 }

                }

         }

原创粉丝点击