测试类Al.java
package cn.annotation.demo1;
import java.lang.reflect.Method;
import org.junit.Test;
public class Al
{
public static void main(String[] args) throws Exception
{
// 获取所有方法,看方法有没有没注解修饰
Class clazz = Class.forName("cn.annotation.demo1.Al");
// 获取所有方法
Method[] methods = clazz.getMethods();
// 循环所有方法
for (Method method : methods) {
// 判断哪些方法被注解修饰了
if( method.isAnnotationPresent(MyTest.class))
{
// 执行
method.invoke(clazz.newInstance(), args);
}
}
}
@MyTest // 功能 :执行该方法
public void test1()
{
System.out.println(1111);
}
@MyTest // 功能 :执行该方法
public void test2()
{
System.out.println(2222);
}
@MyTest // 功能 :执行该方法
public void test3()
{
System.out.println(33333);
}
// 没被注解修饰,不执行该方法
public void test4()
{
System.out.println(444444);
}
}
执行main方法后,控制台输出:
1111
2222
33333
注解MyTest.java
package cn.annotation.demo1;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.LOCAL_VARIABLE;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({METHOD}) // 只对方法有效
@Retention(RetentionPolicy.RUNTIME) // 只对运行时有效
public @interface MyTest // 自定义注解MyTest
{
}