public class StudentImpl {
public void say(String msg) {
System.out.println("Say:" + msg);
}
public void run(Shoes shoes) {
System.out.println(shoes.getColour());
System.out.println(shoes.getMade());
System.out.println(shoes.getSpeed());
}
}
/**
* 方法开始执行
*/
@Before("@annotation(autoLog)")
public void doBefore(JoinPoint point,AutoLog autoLog) {
try {
Class clazz = joinPoint.getTarget().getClass();
String targetName = clazz.getSimpleName();
String methodName = joinPoint.getSignature().getName();
Method methdo = clazz.getMethod(methodName);
if (methdo.getAnnotation(AutoLog.class) != null) {
System.out.println("not null");
} else {
System.out.println("null");
}
} catch (Exception ex) {
System.out.println( ex.toString());
}
}
Method methdo = clazz.getMethod(methodName);这段程序执行报异常:java.lang.NoSuchMethodException
很多网上给的答案都是clazz.getMethod()和clazz.getDeclaredMethod()的区别(前者获得公共方法,后者所有方法),但是问题依旧,经过查资料发现,如果想获得该方法clazz.getMethod()有两个参数,第一参数代表要获得方法名称,第二个参数是方法执行需要的形参类型,代码修改成如下
try {
Class clazz = joinPoint.getTarget().getClass();
String targetName = clazz.getSimpleName();
String methodName = joinPoint.getSignature().getName();
Method methdo = clazz.getMethod(methodName,String.class);
if (methdo.getAnnotation(AutoLog.class) != null) {
System.out.println("not null");
} else {
System.out.println("null");
}
} catch (Exception ex) {
System.out.println( ex.toString());
}
Method methdo = clazz.getMethod(methodName,String.class); 正确写法
但是在实际应用过程中,通过aop反射想获得方法要动态获得方法形参,所以完整代码如下:
try {
Class clazz = joinPoint.getTarget().getClass();
String targetName = clazz.getSimpleName();
String methodName = joinPoint.getSignature().getName();
Class[] parameterTypes = ((MethodSignature)joinPoint.getSignature()).getMethod().getParameterTypes();
Method methdo = clazz.getMethod(methodName,parameterTypes);
if (methdo.getAnnotation(AutoLog.class) != null) {
System.out.println("not null");
} else {
System.out.println("null");
}
} catch (Exception ex) {
ex.toString();
}
这样就可以获得该方法并获得该方法的注解.谢谢