自定义注解:
/*先自己定义1个注解,这个注解运行时能获得信息,修饰方法
*
*
*
* */
package day8yue31;
import java.lang.*;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Testable {
}
在方法上标记注解:
/*
* 测试类
*
* */
package day8yue31;
public class MyTest {
@Testable()
public void method1()
{
System.out.println("method1");
}
public void method2()
{
System.out.println("method2");
}
@Testable()
public void method3()
{
System.out.println("method3");
}
public void method4()
{
System.out.println("method4");
}
@Testable()
public void method5()
{
System.out.println("method5");
}
@Testable()
public void method6()
{
System.out.println("method6");
}
@Testable()
public void method7()
{
System.out.println("method");
}
}
通过标记处理对应的方法:
/* 处理类
*
* */
package day8yue31;
import java.lang.reflect.Method;
public class ProcessorTest {
//处理方法,按照标记来执行对应的方法
public static void process(String classname) throws Exception
{
int passed = 0;
int failed = 0;
//遍历classname对应的类里面所有方法
for(Method m : Class.forName(classname).getMethods())
{
if(m.isAnnotationPresent(Testable.class))
{
try {
m.invoke(null);
passed++;
} catch (Exception e) {
System.out.println("方法"+m+"运行失败");
failed++;
}
}
}
System.out.println("一共运行了"+(failed+passed)+"个方法");
System.out.println("失败了"+(failed)+"个方法");
System.out.println("成功了"+(passed)+"个方法");
}
public static void main(String[] arga) throws Exception
{
process("day8yue31.MyTest");
}
}