###### tags: `java` `java annotation` # 建立Java Annotation ## annotation.java ```java=1 package com.sinosoft.lis.controller.bq; //只是package name import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.Target; import java.lang.annotation.ElementType; /* ElementType.TYPE代表標籤作用於class, ElementType.CONSTRUCTOR代表標籤作用於建構子,多值宣告要 用大括號{ElementType.TYPE,Element.METHOD,Element.CONSTRUCTOR} */ @Target(ElementType.METHOD) @Rentention(RetentionPolicy.RUNTIME) /* 代表標籤作用持續到runtime結束 */ public @interface annotation{ int count() default 1; //annotation變數,非方法, 預設值為1 } ``` ## Test.java ```java=1 package com.sinosoft.lis.controller.bq; public class Test{ @annotation(count=10){ public void run(){ System.out.println("run"); } public void run1(){ System.out.println("run1"); } public void run2(){ System.out.println("run2"); } } } ``` ## mains.java ```java=1 package com.sinosoft.lis.controller.bq; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Iterator; public class mains{ public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException,InvocationTargetException{ Test t1 = new Test(); for(Method method: t1.getClass().getDelcaredMethods()){ //取得t1 class宣告的所有方法 if(method.isAnnotationPresent(annotation.class)){ //確認t1是否有方法前面有定義annotation的標籤 annotation a = method.getAnnotation(annotation.class); //依據annotation宣告的位置取得標籤 for(int i=0;i<a.count();i++) method.invoke(t1); //呼叫t1有宣告annotation的方法 } } } } ``` //執行mains.java,最後會印出10個run.. run run run run run run run run run run