java word批注

在上一篇有关Java注释的文章中,我概述了一个最近的用例,并为您提供了一些自定义注释的示例以及如何使用它们。

在本文中,我将更进一步,并为您提供一些自定义注释的示例,以及如何使用Java Reflection API处理这些自定义注释。 学习完本教程后,您应该对自定义注释可以提供的简单性和灵活性有了更好的了解。 因此,让我们深入研究代码!

自定义注释清单

我今天为示例代码创建了三个不同的注释,分别是DoItLikeThisDoItLikeThatDoItWithAWhiffleBallBat注释。 每个注释针对的是不同的元素类型,并且具有略微不同的属性,因此我可以向您展示如何查找和处理它们。

喜欢这个注释

DoItLikeThis注释针对ElementType TYPE,这使其仅可用于Java类型。 该批注具有三个可选元素description,action和一个布尔字段shouldDoItLikeThis。 如果在使用此注释时未为这些元素提供任何值,则它们将默认为指定的值。

package com.keyhole.jonny.blog.annotations;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;/*** Annotation created for doing it like this.*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface DoItLikeThis {/*** @return - The description.*/String description() default "";/*** @return - The action.*/String action() default "";/*** @return - Should we be doing it like this.*/boolean shouldDoItLikeThis() default false;}

像注释一样

DoItLikeThat注释是仅针对Java字段的注释。 此批注还具有一个类似的布尔元素,名称为ShouldDoItLikeThat,它没有指定默认值,因此在使用批注时是必需的元素。 批注还包含一个定义为String数组的元素,该元素将包含应检查的用户角色列表。

package com.keyhole.jonny.blog.annotations;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;/*** Annotation created for doing it like that* instead of like this.*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DoItLikeThat {/*** @return - Should we be doing it like that.*/boolean shouldDoItLikeThat();/*** @return - List of user roles that can do it like that.*/String[] roles() default{};}

DoWWithAWhiffleBallBat批注

DoItWithAWhiffleBallBat注释旨在仅与方法一起使用,并且与其他注释类似。 它也有一个类似的布尔元素,这个名字叫做shouldDoItWithAWhiffleBallBat。 还定义了另一个元素,该元素使用WhiffleBallBat枚举定义了可用的不同类型的Whiffle Ball bat,默认为经典的黄色经典Whiffle Ball bat。

package com.keyhole.jonny.blog.annotations;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;/*** When you can't do it like this or do it like that,* do it with a whiffle ball bat.*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DoItWithAWhiffleBallBat {/*** @return - Should we be doing it with a whiffle ball bat.*/boolean shouldDoItWithAWhiffleBallBat() default false;/*** @return - Sweet, which type of whiffle ball bat?*/WhiffleBallBat batType() default WhiffleBallBat.YELLOW_PLASTIC;}

带注释的类

现在我们已经为示例定义了注释,我们需要几个类进行注释。 每个类都提供了使用指定元素以及依赖默认值的注释的示例用法。 还包括其他未注释的字段和方法,因此注释处理器不应对其进行处理。 这是两个示例类的源代码:

带注释的一类

package com.keyhole.jonny.blog.annotations;import java.util.Date;@DoItLikeThis
public class AnnotatedOne implements AnnotatedClass {@DoItLikeThat(shouldDoItLikeThat = false)private String field1;@DoItLikeThat(shouldDoItLikeThat = true, roles = { "admin", "root" })private String field2;private String field3;private Date dateDoneLikeThis;/* setters and getters removed for brevity */@DoItWithAWhiffleBallBat(batType = WhiffleBallBat.BLACK_PLASTIC, shouldDoItWithAWhiffleBallBat = true)public void doWhateverItIs() {// method implementation}public void verifyIt() {// method implementation}}

带注释的二级

package com.keyhole.jonny.blog.annotations;import java.util.Date;@DoItLikeThis(action = "PROCESS", shouldDoItLikeThis = true, description = "Class used for annotation example.")
public class AnnotatedTwo implements AnnotatedClass {@DoItLikeThat(shouldDoItLikeThat = true)private String field1;@DoItLikeThat(shouldDoItLikeThat = true, roles = { "web", "client" })private String field2;private String field3;private Date dateDoneLikeThis;/* setters and getters removed for brevity */@DoItWithAWhiffleBallBat(shouldDoItWithAWhiffleBallBat = true)public void doWhateverItIs() {// method implementation}public void verifyIt() {// method implementation}}

处理注释

使用反射来处理注释实际上非常简单。 对于您可以为其创建和应用注释的每种元素类型,这些元素上都有一些使用注释的方法。 您需要做的第一件事是检查元素以确定是否有任何注释,或检查该元素是否存在特定注释。

每个元素类型Class,Field和Method都实现了AnnotatedElement接口,该接口定义了以下方法:

  • getAnnotations() –返回此元素上存在的所有注释,包括所有继承的注释。
  • getDeclaredAnnotations() –仅返回直接存在于此元素上的注释。
  • getAnnotation(Class <A>注记类) –返回指定注解类型的元素注解,如果找不到,则返回null。
  • isAnnotation() –如果要检查的元素是注释,则返回true。
  • isAnnotationPresent(Class <?Extends Annotation>注解类) –如果所检查的元素上存在指定的注解,则返回true。

在处理批注时,我们要做的第一件事是检查批注是否存在。 为此,我们将对批注处理进行以下检查:

if (ac.getClass().isAnnotationPresent(DoItLikeThis.class)) {// process the annotation, "ac" being the instance of the object we are inspecting}

找到所需的批注后,我们将获取该批注并为该批注进行任何处理。 至此,我们将可以访问注释的元素及其值。 请注意,没有任何用于访问注释元素的获取器或设置器。

DoItLikeThis anno = ac.getClass().getAnnotation(DoItLikeThis.class);System.out.println("Action: " + anno.action());System.out.println("Description: " + anno.description());System.out.println("DoItLikeThis:" + anno.shouldDoItLikeThis());

对于字段和方法,检查当前注释会略有不同。 对于这些类型的元素,我们需要遍历所有字段或方法以确定元素上是否存在注释。 您将需要从Class中获取所有字段或方法,遍历Field或Method数组,然后确定元素上是否存在注释。 看起来应该像这样:

Field[] fields = ac.getClass().getDeclaredFields();for (Field field : fields) {if (field.isAnnotationPresent(DoItLikeThat.class)) {DoItLikeThat fAnno = field.getAnnotation(DoItLikeThat.class);System.out.println("Field: " + field.getName());System.out.println("DoItLikeThat:" + fAnno.shouldDoItLikeThat());for (String role : fAnno.roles()) {System.out.println("Role: " + role);}}}

结论

如您所见,创建自己的注释并对其进行处理非常简单。 在我提供的示例中,我们只是将元素的值输出到控制台或日志。 希望您能看到这些的潜在用途,并且将来可能会真正考虑创建自己的。 我在注释中看到的一些最佳用法是它们替换一些配置代码或经常使用的通用代码,例如验证字段的值或将业务对象映射到Web表单。

最后,这是完整的源代码以及用于执行代码的简单Java主类:

带注释的类处理器

package com.keyhole.jonny.blog.annotations;import java.lang.reflect.Field;
import java.lang.reflect.Method;public class AnnotatedClassProcessor {public void processClass(AnnotatedClass ac) {System.out.println("------Class Processing Begin---------");System.out.println("Class: " + ac.getClass().getName());if (ac.getClass().isAnnotationPresent(DoItLikeThis.class)) {// process the annotation, "ac" being the instance of the object we are inspectingDoItLikeThis anno = ac.getClass().getAnnotation(DoItLikeThis.class);System.out.println("Action: " + anno.action());System.out.println("Description: " + anno.description());System.out.println("DoItLikeThis:" + anno.shouldDoItLikeThis());System.out.println("------Field Processing---------");Field[] fields = ac.getClass().getDeclaredFields();for (Field field : fields) {if (field.isAnnotationPresent(DoItLikeThat.class)) {DoItLikeThat fAnno = field.getAnnotation(DoItLikeThat.class);System.out.println("Field: " + field.getName());System.out.println("DoItLikeThat:" + fAnno.shouldDoItLikeThat());for (String role : fAnno.roles()) {System.out.println("Role: " + role);}}}System.out.println("------Method Processing---------");Method[] methods = ac.getClass().getMethods();for (Method method : methods) {if ( method.isAnnotationPresent(DoItWithAWhiffleBallBat.class)) {DoItWithAWhiffleBallBat mAnno = method.getAnnotation(DoItWithAWhiffleBallBat.class);System.out.println("Use WhiffleBallBat? " + mAnno.shouldDoItWithAWhiffleBallBat());System.out.println("Which WhiffleBallBat? " + mAnno.batType());}}}System.out.println("------Class Processing End---------");}
}

运行处理器

package com.keyhole.jonny.blog.annotations;public class RunProcessor {/*** @param args*/public static void main(String[] args) {AnnotatedClassProcessor processor = new AnnotatedClassProcessor();processor.processClass(new AnnotatedOne());processor.processClass(new AnnotatedTwo());}}

翻译自: https://www.javacodegeeks.com/2014/09/processing-java-annotations-using-reflection.html

java word批注

java word批注_使用反射处理Java批注相关推荐

  1. pdf.js批注_使用反射处理Java批注

    pdf.js批注 在上一篇有关Java注释的文章中,我概述了一个最近的用例,并为您提供了一些自定义注释的示例以及如何使用它们. 在本文中,我将更进一步,并提供一些自定义注释的示例,以及如何使用Java ...

  2. java 委托机制_通过反射实现Java下的委托机制代码详解

    简述 一直对Java没有现成的委托机制耿耿于怀,所幸最近有点时间,用反射写了一个简单的委托模块,以供参考. 模块API public Class Delegater()//空参构造,该类管理委托实例并 ...

  3. java word批注_创建自己的Java批注

    java word批注 如果您一直在用Java编程并且使用诸如Spring和Hibernate之类的任何流行框架,那么您应该对使用注释非常熟悉. 当使用现有框架时,其注释通常就足够了. 但是,您是否发 ...

  4. java委托机制教程_通过反射实现Java下的委托机制代码详解

    简述 一直对java没有现成的委托机制耿耿于怀,所幸最近有点时间,用反射写了一个简单的委托模块,以供参考. 模块api public class delegater()//空参构造,该类管理委托实例并 ...

  5. java word流_(word)java中字节流示例.doc

    (word)java中字节流示例 OutputStream和InputStream分别为java中IO包整个字节输入/输出流的的主类: public abstract class InputStrea ...

  6. java python算法_用Python,Java和C ++示例解释的排序算法

    java python算法 什么是排序算法? (What is a Sorting Algorithm?) Sorting algorithms are a set of instructions t ...

  7. 做Java头发少_这35个Java代码优化细节,你用了吗

    链接:https://www.jianshu.com/p/6e472304b5ac 前言 代码 优化 ,一个很重要的课题.可能有些人觉得没用,一些细小的地方有什么好修改的,改与不改对于代码的运行效率有 ...

  8. java 判断类型_如何快速入门Java编程学习(干货)

    一.初识Java 1.生活中的程序: 从起床到教室上课的过程 穿衣打扮>起床>洗漱>出宿舍>>吃早餐>到教室 按照特定的顺序去完成某一件事的过程我们叫做生活中的程序 ...

  9. java 异常信息_优雅的异常处理 -- Java中的异常

    处理异常自己处理 try-catch抛出让别人处理 throws 获得异常信息 直接打印异常对象 通过异常对象调用getMessage()方法获得 通过异常对象调用printStackTrace()方 ...

最新文章

  1. eclipse 无法使用注解的两个解决方法
  2. codevs 1013 求先序排列
  3. Star PDF Watermark Ultimate中文版
  4. Android攻城狮ListView
  5. git命令行完全解读
  6. The Ransom of Red Chief
  7. 将list中的元素按照属性分类成树状的map
  8. tomcat 5 comcat 6 区别
  9. vue按钮Button
  10. JUnit 5 Alpha版本简化了单元测试
  11. 谷歌用3亿张图做了个深度学习实验,结论:数据还是越大越好
  12. 当VR踏入足球赛事会是如何?用数学运算又是如何?
  13. 未明学院:都知道智商、情商、逆商,可你知道“搜商”吗?
  14. 路由器 三层交换机 网关有什么区别
  15. 微信分享图片URL不显示问题
  16. win10无法使用内置管理员账户打开应用怎么办
  17. String字符串操作--切割,截取,替换,查找,比较,去空格.....
  18. ABAP WB01 BDC ”No batch input data for screen “ ”没有屏幕 的批输入数据“
  19. 单因素方差分析与卡方检验有什么区别,能否举个例子?
  20. C++基础-介绍·数据结构·排序·算法

热门文章

  1. ssl1341-最小路径覆盖【最大匹配,最小路径覆盖,图论】
  2. 【图论】【斜率优化】前往大都会(loj 2769)
  3. 一些来自STL的好东西
  4. 响应式布局(手机端)
  5. 试编写算法,设任意n个整数存放于数组A[1...n]中,将所有正数排在所有负数前面(要求:算法时间复杂度为O(n))
  6. 你知道i=i++;的含义吗?原理其实没有你想的那么简单
  7. 《白鹿原》金句摘抄(五)
  8. 人脸检测源码facedetection
  9. idea创建标准的meaven项目
  10. 常用的数据交换格式有哪些_高程数据格式介绍