我在学习SpringAop的时候了解到spring的底层实现基本是靠注解加反射。就像自己写个非常小的测试代码试一试。但在这个过程中遇到了一些小的插曲。
我想通过反射调用某个对象所持有的方法中被@Tag所标记的部分,下面是我的代码:
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.reflect.Method;
import java.lang.annotation.RetentionPolicy;
public class Test {
public static void main(String[] args) throws Exception {
Class<Test> t=Test.class; //获取Class对象
Method[] m=t.getMethods(); //获取方法集合
for(Method mm : m) { //遍历方法
if(mm.toString().contains("m(")) //打印测试方法
System.out.println("\nmethod print:\t"+mm);
for(Annotation a : mm.getAnnotations()) { //遍历方法注解
if((a.getClass()==Tag.class)) {
System.out.print("method invoke:\t");
mm.invoke(new Test(), 666); //调用方法
}
}
}
}
@Tag //测试方法
public void m(int n) {
System.out.println("method m(int