java word批注_使用反射处理Java批注
java word批注
在上一篇有關Java注釋的文章中,我概述了一個最近的用例,并為您提供了一些自定義注釋的示例以及如何使用它們。
在本文中,我將更進一步,并為您提供一些自定義注釋的示例,以及如何使用Java Reflection API處理這些自定義注釋。 學習完本教程后,您應該對自定義注釋可以提供的簡單性和靈活性有了更好的了解。 因此,讓我們深入研究代碼!
自定義注釋清單
我今天為示例代碼創建了三個不同的注釋,分別是DoItLikeThis , DoItLikeThat和DoItWithAWhiffleBallBat注釋。 每個注釋針對的是不同的元素類型,并且具有略微不同的屬性,因此我可以向您展示如何查找和處理它們。
喜歡這個注釋
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批注的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 安卓上的模拟器平台(安卓上的模拟器)
- 下一篇: 去备案改色膜被发现改了排气(去备案改色)