Annotation之標記註解

自定義的註解,該註解沒有任何成員變量,僅僅是一個標記Annotaion

package annotation_;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 僅僅是註解標記
 * @desc 標記程序元素 是可以測試的
 * @author 楊潤康Bla
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Testable {

}

寫一個用於測試標記註解的類

package annotation_;
/**
 * 用於測試的目標類
 * @author 楊潤康Bla
 */
public class TargetTestClass {
    //只要是使用 @Testable 註解標記的,都表明只是可測試
    @Testable
    public static void m1(){
        System.out.println("Test....m1");
    }

    @Testable
    public static void m2(){
        System.out.println("Test....m2");
    }

    public static void m3(){
        System.out.println("Test....m3");
    }

    @Testable
    public static void m4(){
        System.out.println("Test....m4");
    }

    @Testable
    public static void m5(){
        throw new IllegalArgumentException("m5 Exception...");//需要將異常拋出
    }

    public static void m6(){
        System.out.println("Test....m6");
    }

    @Testable
    public static void m7(){
        throw new RuntimeException("m7 Exception..."); //需要將異常拋出
    }

    @Testable
    public static void m8(){
        System.out.println("Test....m8");
    }

}

標記註解本身對程序是沒有任何影響的,僅僅是標記作用,所以寫一個註解的處理工具,讓我們寫的註解(標記註解或其他自定義、非自定義註解)產生實際作用

package annotation_;

import java.lang.reflect.Method;

/**
 *註解處理工具
 */
public class AnnotationProcessorTool {

    public static void process(String clazz) throws Exception{

        Integer successCount = 0;
        Integer failedCount = 0;

        Method[] methods = Class.forName(clazz).getMethods();
        for(Method method : methods){
            if(method.isAnnotationPresent(Testable.class)){ //如果是被Testable註解類註解的
                try {
                    method.invoke(null);
                    successCount++;
                } catch (Exception e) {
                    System.out.println(method.getName() +"異常:"+ e.getCause());
                    failedCount++;
                }
            }
        }

        System.out.println("一共運行了" + (successCount+failedCount) + "個測試方法");
        System.out.println("成功運行了" + successCount + "個測試方法");
        System.out.println("失敗了" + failedCount + "個測試方法");
    }
}

最後,寫個測試類測試一下吧

package annotation_;

public class MainTest {
    public static void main(String[] args) throws Exception {
        String clazz = TargetTestClass.class.getName();
        AnnotationProcessorTool.process(clazz);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章