日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > java >内容正文

java

使用反射处理Java批注

發(fā)布時間:2023/12/3 java 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 使用反射处理Java批注 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

在上一篇有關(guān)Java注釋的文章中,我概述了一個最近的用例,并為您提供了一些自定義注釋的示例以及如何使用它們。

在本文中,我將更進(jìn)一步,并為您提供一些自定義注釋的示例,以及如何使用Java Reflection API處理這些自定義注釋。 學(xué)習(xí)完本教程后,您應(yīng)該對自定義注釋可以提供的簡單性和靈活性有了更好的了解。 因此,讓我們深入研究代碼!

自定義注釋清單

我今天為示例代碼創(chuàng)建了三個不同的注釋,分別是DoItLikeThisDoItLikeThatDoItWithAWhiffleBallBat注釋。 每個注釋針對的是不同的元素類型,并且具有稍微不同的屬性,因此我可以向您展示如何查找和相應(yīng)地處理它們。

喜歡這個注釋

DoItLikeThis注釋針對ElementType TYPE,這使其僅可用于Java類型。 該批注具有三個可選元素description,action和一個布爾字段shouldDoItLikeThis。 如果在使用此批注時不為這些元素提供任何值,則它們將默認(rèn)為指定的值。

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,它沒有指定默認(rèn)值,因此在使用批注時是必選元素。 批注還包含一個定義為String數(shù)組的元素,該元素將包含應(yīng)檢查的用戶角色列表。

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球棒,默認(rèn)為經(jīng)典的黃色經(jīng)典Whiffle球棒。

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;}

帶注釋的類

現(xiàn)在我們已經(jīng)為示例定義了注釋,我們需要幾個類進(jìn)行注釋。 每個類都提供了使用指定元素以及依賴默認(rèn)值的注釋的示例用法。 還包括其他未注釋的字段和方法,因此注釋處理器不應(yīng)對其進(jìn)行處理。 這是兩個示例類的源代碼:

帶注釋的一類

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}}

處理注釋

使用反射來處理注釋實際上非常簡單。 對于您可以為其創(chuàng)建和應(yīng)用注釋的每種元素類型,這些元素上都有一些使用注釋的方法。 您需要做的第一件事是檢查元素以確定是否有任何注釋或檢查該元素是否存在特定注釋。

每個元素類型Class,Field和Method都實現(xiàn)了AnnotatedElement接口,該接口定義了以下方法:

  • getAnnotations() –返回此元素上存在的所有注釋,包括所有繼承的注釋。
  • getDeclaredAnnotations() –僅返回直接存在于此元素上的注釋。
  • getAnnotation(Class <A>注記類) –返回指定注解類型的元素注解,如果找不到,則返回null。
  • isAnnotation() –如果要檢查的元素是注釋,則返回true。
  • isAnnotationPresent(Class <?Extends Annotation>注解類) –如果所檢查的元素上存在指定的注解,則返回true。

在處理批注時,我們要做的第一件事是檢查批注是否存在。 為此,我們將對批注處理進(jìn)行以下檢查:

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

找到所需的批注后,我們將獲取該批注并為該批注進(jìn)行任何處理。 至此,我們將可以訪問注釋的元素及其值。 請注意,沒有任何用于訪問注釋元素的獲取器或設(shè)置器。

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());

對于字段和方法,檢查當(dāng)前注釋會略有不同。 對于這些類型的元素,我們需要遍歷所有字段或方法以確定元素上是否存在注釋。 您將需要從Class中獲取所有字段或方法,遍歷Field或Method數(shù)組,然后確定元素上是否存在注釋。 看起來應(yīng)該像這樣:

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);}}}

結(jié)論

如您所見,創(chuàng)建自己的注釋并進(jìn)行處理非常簡單。 在我提供的示例中,我們只是將元素的值輸出到控制臺或日志。 希望您能看到這些的潛在用途,并且將來可能會真正考慮創(chuàng)建自己的。 我在注釋中看到的一些最佳用法是,它們替換一些配置代碼或經(jīng)常使用的通用代碼,例如驗證字段的值或?qū)I(yè)務(wù)對象映射到Web表單。

最后,這是完整的源代碼以及一個簡單的Java主類來執(zhí)行代碼:

帶注釋的類處理器

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

總結(jié)

以上是生活随笔為你收集整理的使用反射处理Java批注的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。