版权声明:From Lay https://blog.csdn.net/Sadlay/article/details/83964366
AOP通过连接点获取Method异常 java.lang.NoSuchMethodException
问题
在用AOP做日志的时候,出现了java.lang.NoSuchMethodException无法获得Method的异常。
原方法
/**
* 获取日志注解参数
* @param joinPoint
* @return
* @Date 2018年11月7日 下午3:52:54
* @Author lay
*/
public LogApi getLogApi(JoinPoint joinPoint) {
Object[] args = joinPoint.getArgs();
Class<?>[] argTypes = new Class[joinPoint.getArgs().length];
for (int i = 0; i < args.length; i++) {
argTypes[i] = args[i].getClass();
}
Method method = null;
try {
method = joinPoint.getTarget().getClass().getMethod(joinPoint.getSignature().getName(), argTypes);
}
catch (NoSuchMethodException e) {
e.printStackTrace();
}
catch (SecurityException e) {
e.printStackTrace();
}
LogApi logApi = method.getDeclaredAnnotation(LogApi.class);
return logApi;
}
原本是通过连接点JoinPoint
获得目标对象方法的参数和方法名,在通过目标对象的getMethod
的方法获得Method对象。
这段代码在我刚写完的测试中是没有问题的,但是在标注到下面的方法上就抛出了NoSuchMethodException
异常。
@Override
@LogApi(logType = SysLogType.SYS_STAFF_OPER_LOG, systemType = SystemType.SYSTEM_TYPE_SYSMANM, comandType = Operation.FIND_PASSWROD)
public String updateFindPassword(Map map) {
//..具体方法省略
}
这里是通过Postman
进行模拟参数测试的。
原因
在通过几次测试后,我发现问题出现在方法的参数上。
为了测试,我将原代码参数类型写成Map.class
method = joinPoint.getTarget().getClass().getMethod(joinPoint.getSignature().getName(), Map.class);
这样就没有问题。
经过打断点发现,postman
模拟的Map
参数自动实例化成LinkedHashMap
,那么我通过遍历参数获得参数的class类型时就是LinkedHashMap.class
而不是Map.class
,这样我根据参数类型LinkedHashMap.class
去获得方法就会报出java.lang.NoSuchMethodException
异常。
解决办法
使用 MethodSignature
的getMethod()
方法。
修改代码如下
扫描二维码关注公众号,回复:
4300620 查看本文章
/**
* 获取日志注解参数
* @param joinPoint
* @return
* @Date 2018年11月7日 下午3:52:54
* @Author lay
*/
public LogApi getLogApi(JoinPoint joinPoint) throws NoSuchMethodException {
MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
Method method = null;
method = methodSignature.getMethod();
LogApi logApi = method.getDeclaredAnnotation(LogApi.class);
return logApi;
}
这样就好了。