1、要求
自定义注解MyTest,使用main方法模拟测试类的启动按钮,实现有MyTest注解标注的方法就要触发执行。
2、代码实现
package com.zjl.study.注解.注解模拟junit框架;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
/**
* Created by zjl 2022/6/21
**/
public class MyJunit {
// main方法模拟测试类的启动按钮,实现有MyTest注解标注的方法就要触发执行。
public static void main(String[] args) throws Exception {
MyJunit myJunit = new MyJunit();
// 1、得到类对象
Class<MyJunit> myJunitClass = MyJunit.class;
// 2、获取类中全部方法对象
Method[] methods = myJunitClass.getDeclaredMethods();
// 3、遍历全部方法,有注解就触发执行
for (Method method : methods) {
if(method.isAnnotationPresent(MyTest.class)){
// 触发此方法执行
method.invoke(myJunit);
}
}
}
@MyTest
public void test01(){
System.out.println("====test01====");
}
public void test02(){
System.out.println("====test02====");
}
@MyTest
public void test03(){
System.out.println("====test03====");
}
}
@Target(ElementType.METHOD) // 只能注解方法
@Retention(RetentionPolicy.RUNTIME) // 运行时能够保留该注解
@interface MyTest{
}
3、运行结果
test01和test03方法有注解,会触发执行,test02没有注解,不触发执行。