1 案例說明
- 模擬Junit測試的@Test
2 案例分析
- 模擬Junit測試的注釋@Test,首先需要編寫自定義注解@MyTest,並添加元注解,保證自定義注解只能修飾方法,且在運行時可以獲得。
- 然后編寫目標類(測試類),然后給目標方法(測試方法)使用 @MyTest注解,編寫三個方法,其中兩個加上@MyTest注解。
- 最后編寫調用類,使用main方法調用目標類,模擬Junit的運行,只要有@MyTest注釋的方法都會運行。
3 案例代碼
自定義的MyTest注解:
package com.homework_test.test03;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyTest {
}
在Test實體類上使用注解:
package com.homework_test.test03;
public class Test {
@MyTest
public void show01() {
System.out.println("show01()方法!!!");
}
// @MyTest
public void show02() {
System.out.println("show02()方法!!!");
}
@MyTest
public void show03() {
System.out.println("show03()方法!!!");
}
}
測試:
package com.homework_test.test03;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class AnnotationTest {
public static void main(String[] args) throws IllegalAccessException, InstantiationException, InvocationTargetException {
//獲得Test實體類class對象
Class<Test> testClass = Test.class;
//獲取該實體對象(執行方法使用)
Test test = testClass.newInstance();
//獲取所有成員方法
Method[] methods = testClass.getMethods();
//遍歷方法集合對象並判斷
for (Method method : methods) {
//判斷method方法是否含有MyTest注解
if(method.isAnnotationPresent(MyTest.class)){
//含有,直接執行方法
method.invoke(test);
}
}
}
}
/*
打印結果:
show01()方法!!!
show03()方法!!!
*/