自定义mytest注解
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 {
}
实现该注解 的功能
import java.lang.reflect.Method;
public class MyTestDemo {
/*
* 自己编写一个单元测试的注解,Mytest
* 使用了该注解的方法可以直接运行
*
* */
public static void main(String[] args) throws Exception {
//1.获取该类的class文件对象
Class<?> clazz = Class.forName("TestClass");
//快速创建该类的对象,用于执行方法时作为参数传递
Object o = clazz.newInstance();
//2.得到该文件对象上的所有方法
Method[] methods = clazz.getMethods();
//3.遍历所有的方法,查看上面手否还有注解,注意:isAnnotationPresent中传递的是注解的class文件对象
for (Method m : methods) {
if (m.isAnnotationPresent(MyTest.class)){
//如果有该注解,就执行该方法
m.invoke(o);
}
}
}
}
编写一个类,在方法中测试该注解
public class TestClass {
@MyTest
public void method01(){
System.out.println("我是方法1");
}
public void method02(){
System.out.println("我是方法2");
}
@MyTest
public void method03(){
System.out.println("我是方法3");
}
}