首页 > 编程 > Java > 正文

JAVA注解应用

2019-11-06 06:32:46
字体:
来源:转载
供稿:网友
博客微博相册收藏留言关于我
 

java注解应用实例 - Annotation, 自定义注解, 注解类规则

博客分类: javaJava 注解Annotationjava注解应用实例java反射 

本文介绍了java的自定义注解及注解类编写的规则, 并通过实例来说明下如何使用java的注解. 实例演示了注解在类,构造方法,方法和字段的使用. 可以从这里下载到完成的工程代码: http://dl.iteye.com/topics/download/f74972df-234f-30c9-aadd-ca2ed1376bc2

自定义注解类编写的一些规则:

1. Annotation型定义为@interface, 所有的Annotation会自动继承java.lang.Annotation这一接口,并且不能再去继承别的类或是接口.

2. 参数成员只能用public或默认(default)这两个访问权修饰

3. 参数成员只能用基本类型byte,short,char,int,long,float,double,boolean八种基本数据类型和String、Enum、Class、annotations等数据类型,以及这一些类型的数组.

4. 要获取类方法和字段的注解信息,必须通过Java的反射技术来获取 Annotation对象,因为你除此之外没有别的获取注解对象的方法

5. 注解也可以没有定义成员, 不过这样注解就没啥用了

自定义注解类时, 可以指定目标 (类、方法、字段, 构造函数等) , 注解的生命周期(运行时,class文件或者源码中有效), 是否将注解包含在javadoc中及是否允许子类继承父类中的注解, 具体如下: 

1. @Target 表示该注解目标,可能的 ElemenetType 参数包括:

ElemenetType.CONSTRUCTOR 构造器声明ElemenetType.FIELD 域声明(包括 enum 实例) ElemenetType.LOCAL_VARIABLE 局部变量声明 ElemenetType.METHOD 方法声明 ElemenetType.PACKAGE 包声明 ElemenetType.PARAMETER 参数声明 ElemenetType.TYPE 类,接口(包括注解类型)或enum声明

2. @Retention 表示该注解的生命周期,可选的 RetentionPolicy 参数包括

RetentionPolicy.SOURCE 注解将被编译器丢弃 RetentionPolicy.CLASS 注解在class文件中可用,但会被VM丢弃 RetentionPolicy.RUNTIME VM将在运行期也保留注释,因此可以通过反射机制读取注解的信息

3. @Documented 指示将此注解包含在 javadoc 中

4.  @Inherited 指示允许子类继承父类中的注解

好, 该介绍的介绍了, 看下自定义的注解应用实例:

1. 首先看下定义的注解类:

类注解定义, MyClassAnnotation.java:

[java] view plain copypackage  com.ross.annotation;  import  java.lang.annotation.*;  /**   * Author: Jiangtao He; Email: ross.jiangtao.he@Gmail.com   * Date: 2012-1-29   * Since: MyJavaExpert v1.0   * Description: class annotation   */   @Retention (RetentionPolicy.RUNTIME)   @Target (ElementType.TYPE)   public   @interface  MyClassAnnotation   {      String uri();      String desc();  }  默认构造方法注解定义,MyConstructorAnnotation.java: [java] view plain copypackage  com.ross.annotation;  import  java.lang.annotation.ElementType;  import  java.lang.annotation.Retention;  import  java.lang.annotation.RetentionPolicy;  import  java.lang.annotation.Target;  /**   * Author: Jiangtao He; Email: ross.jiangtao.he@gmail.com   * Date: 2012-1-29   * Since: MyJavaExpert v1.0   * Description: Constructor annotation   */   @Retention (RetentionPolicy.RUNTIME)   @Target (ElementType.CONSTRUCTOR)   public   @interface  MyConstructorAnnotation   {      String uri();      String desc();  }  方法注解定义,MyMethodAnnotation.java:[java] view plain copypackage  com.ross.annotation;  import  java.lang.annotation.ElementType;  import  java.lang.annotation.Retention;  import  java.lang.annotation.RetentionPolicy;  import  java.lang.annotation.Target;  /**   * Author: Jiangtao He; Email: ross.jiangtao.he@gmail.com   * Date: 2012-1-29   * Since: MyJavaExpert v1.0   * Description: method annotation   */   @Retention (RetentionPolicy.RUNTIME)   @Target (ElementType.METHOD)   public   @interface  MyMethodAnnotation   {      String uri();      String desc();  }  字段注解定义, MyFieldAnnotation.java:[java] view plain copypackage  com.ross.annotation;  import  java.lang.annotation.ElementType;  import  java.lang.annotation.Retention;  import  java.lang.annotation.RetentionPolicy;  import  java.lang.annotation.Target;  /**   * Author: Jiangtao He; Email: ross.jiangtao.he@gmail.com   * Date: 2012-1-29   * Since: MyJavaExpert v1.0   * Description: field annotation   */   @Retention (RetentionPolicy.RUNTIME)   @Target (ElementType.FIELD)   public   @interface  MyFieldAnnotation   {      String uri();      String desc();  }  2. 再看下我们注解的应用和测试:

在类上面使用了MyClassAnnotation注解, 默认构造方法上使用了MyConstructorAnnotation注解,  自定义方法上使用了MyMethodAnnotation注解, 自定义字段上使用了MyFieldAnnotation注解, 在Mail函数中则实现了访问这些注解,并打印注解信息.

MySample.java:

[java] view plain copypackage  com.ross.annotation;  import  java.lang.reflect.*;  /**   * Author: Jiangtao He; Email: ross.jiangtao.he@gmail.com   * Date: 2012-1-29   * Since: MyJavaExpert v1.0   * Description: This class is used to show how to use the annotation of each level   */   @MyClassAnnotation (uri =  "com.ross.MySample" , desc =  "The class name" )  public   class  MySample  {      @MyFieldAnnotation (uri =  "com.ross.MySample#id" , desc =  "The class field" )      public  String id;        /**       * Description: default constructor       */       @MyConstructorAnnotation (uri =  "com.ross.MySample#MySample" , desc =  "The default constuctor" )      public  MySample()      {      }        /**       * Description: normal method       */       @MyMethodAnnotation (uri =  "com.ross.MySample#setId" , desc =  "The class method")      public   void  setId(String id)      {          this .id = id;      }        /**       * Description: MyAnnotation test       * @throws NoSuchMethodException        * @throws SecurityException        * @throws NoSuchFieldException        */       public   static   void  main(String[] args)  throws  SecurityException,              NoSuchMethodException, NoSuchFieldException      {          MySample oMySample = new  MySample();          // get class annotation           MyClassAnnotation oMyAnnotation = MySample.class                   .getAnnotation(MyClassAnnotation.class );          System.out.PRintln("Class's uri: "  + oMyAnnotation.uri() +  "; desc: "                   + oMyAnnotation.desc());            // get constructor annotation           Constructor oConstructor = oMySample.getClass().getConstructor();          MyConstructorAnnotation oMyConstructorAnnotation = (MyConstructorAnnotation) oConstructor                  .getAnnotation(MyConstructorAnnotation.class );          System.out.println("Constructor's uri: "                   + oMyConstructorAnnotation.uri() + "; desc: "                   + oMyConstructorAnnotation.desc());            // get method annotation           Method oMethod = oMySample.getClass().getDeclaredMethod("setId" ,String. class);          MyMethodAnnotation oMyMethodAnnotation = oMethod                  .getAnnotation(MyMethodAnnotation.class );          System.out.println("Method's uri: "  + oMyMethodAnnotation.uri()                  + "; desc: "  + oMyMethodAnnotation.desc());            // get field annotation           Field oField = oMySample.getClass().getDeclaredField("id" );          MyFieldAnnotation oMyFieldAnnotation = oField                  .getAnnotation(MyFieldAnnotation.class );          System.out.println("Field's uri: "  + oMyFieldAnnotation.uri()                  + "; desc: "  + oMyFieldAnnotation.desc());        }    }  

控制台打印结果:

[plain] view plain copyClass's uri: com.ross.MySample; desc: The class name  Constructor's uri: com.ross.MySample#MySample; desc: The default constuctor  Method's uri: com.ross.MySample#setId; desc: The class method  Field's uri: com.ross.MySample#id; desc: The class field  

至此本实例就完成了, 其实就是抓住两点一个是定义注解类,另外一个是如何访问注解, 就算是学会了.

注: 转载请注明出处: http://hejiangtao.iteye.com ,  用于商业得给我分成大笑

MyJavaExpert_V1.0-java注解应用实例.rar (10.1 KB)下载次数: 2404 顶3 踩分享到:  Java Compiler 应用实例 | Java 序列化的高级认识--序列化反序列化, ...2012-01-29 21:35浏览 18605评论(1)分类:编程语言相关推荐
参考知识库
人工智能知识库10736  关注 | 521  收录Python知识库20226  关注 | 1334  收录Java SE知识库23461  关注 | 468  收录微信开发知识库19036  关注 | 776  收录
评论
1 楼 beiyeren 2013-03-02  写的不错啊
发表评论

 您还没有登录,请您登录后再发表评论

hejiangtao浏览: 75596 次性别: Icon_minigender_1来自: 杭州
最近访客 更多访客>>
wtxczwtxczsnowrainbow东林碣石hello2017
文章分类
全部博客 (13)java (12)网络 (1)网络编程 (1)
社区版块
我的资讯 (0)我的论坛 (0)我的问答 (0)
存档分类
2012-10 (2)2012-03 (1)2012-02 (1)更多存档...
最新评论
砚台观月: 你好,例子还有吗,我想要份学习看下。提供的链接找不到了。java网络编程之Http多线程下载应用实例xianghanscce: ...java泛型应用实例 - 自定义泛型类,方法yhx1231: ...Java反射应用实例beiyeren: 写的不错啊java注解应用实例 - Annotation, 自定义注解, 注解类规则xuanxuan.good: 请问你是如何测试的.谢谢java反射的性能问题 (转)

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表