浅谈java的注解

来源:互联网 发布:java面向对象总结 编辑:程序博客网 时间:2024/06/06 09:55

-----------------------------Java培训、Android培训、iOS培训、.Net培训 期待与您交流----------------------------

 

浅谈java的注解

 

首先明白什么是注解:

               注解就是对的某一事物或行为提供解释说明,以便后来者了解这些事物,java中就是对某些方法,类,参数,变量添加注释,让后来者可以通过反射手段获取这些信息

 

java注解包括那些:

           在java中包含:

三个默认注解,

             @override :重写标志

             @suppresswaring :编译时忽略警告

             @Deprecated:声明成员变量,方法,类已过世

四个元注解:

           @Target:声明该注解的作用范围

                       如:

                             1. ElementType.CONSTRUCTOR:用于描述构造器
                 2.ElementType.FIELD:用于描述域
                 3.ElementType.LOCAL_VARIABLE:用于描述局部变量
                 4.ElementType.METHOD:用于描述方法
                 5.ElementType.PACKAGE:用于描述包
                 6.ElementType.PARAMETER:用于描述参数
                 7.ElementType.TYPE:用于描述类、接口(包括注解类型) 或enum声明                                  

          @Retention:用于声明该注解存在的与那个阶段

                      如:

                               1. RetentionPolicy.RUNTIME:存在于运行阶段

                               2.RetentionPolicy.SOURCE:存在于代码

                              3.RetentionPolicy.CLASS:存在于编译阶段

          @Documented :标注程序成为公共API,可被javadoc生成到文档中

         @Inherited:该注解可被标注了的class类的子类继承

 

如何自定义注解:

跟定义Class差不多,只不过定义的class变成了@Interfacce

 注解中可以使用的数据类型有:

                  1.byte  char  short  int  float  double  long  boolean  byte[]  char[]  short[]  int[]  float[]  double[]  long[]  boolean[]

                  2.String String[]

                  3.Class Class[]

                  4.Enum Enum[]

                  5.Annotation Annotation[]

 

 

如何利用注解:

   利用反射的方法来得到注解并运用注解

1,判断该类是否含有某注解

                  类class.isAnnotationPresent(注解class))        

2,获取注解

                     类class.getAnnotation(注解class);   

3,运用注解

                   用得到的注解对象,调用该注解存在的属性即可

 

下面是代码示例:

public @interface MetaAnnotation {String birthday();}


 

@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.METHOD,ElementType.TYPE})public @interface MyAnnotation { String color(); String value() default "I am a man"; int[] arr() default {1,2,3}; MetaAnnotation metaAnnotation() default @MetaAnnotation(birthday="我的出生日期1990-02-08");}
<pre class="html" name="code">@MyAnnotation(color="red")public class AnnotationTest {public static void main(String[] args) {// TODO Auto-generated method stubif(AnnotationTest.class.isAnnotationPresent(MyAnnotation.class)){MyAnnotation myAnnotation = AnnotationTest.class.getAnnotation(MyAnnotation.class);System.out.println(myAnnotation);String color = myAnnotation.color();System.out.println(color);String value = myAnnotation.value();System.out.println(value);int[] arr = myAnnotation.arr();for(int v : arr){System.out.println(v);}    MetaAnnotation metaAnnotation = myAnnotation.metaAnnotation();    String birthday = metaAnnotation.birthday();    System.out.println(birthday);}}}



 

                  

 

                  

0 0
原创粉丝点击