Spring 从ProceedingJoinPoint获取java.lang.reflect.Method?
问题很简单:有没有办法从apsectj ProceedingJoinPoint获取方法对象 目前我正在做Spring 从ProceedingJoinPoint获取java.lang.reflect.Method?,spring,jakarta-ee,aop,aspectj,spring-aop,Spring,Jakarta Ee,Aop,Aspectj,Spring Aop,问题很简单:有没有办法从apsectj ProceedingJoinPoint获取方法对象 目前我正在做 Class[] parameterTypes = new Class[joinPoint.getArgs().length]; Object[] args = joinPoint.getArgs(); for(int i=0; i<args.length; i++) { if(args[i] != null) { parameterTypes[i] = args
Class[] parameterTypes = new Class[joinPoint.getArgs().length];
Object[] args = joinPoint.getArgs();
for(int i=0; i<args.length; i++) {
if(args[i] != null) {
parameterTypes[i] = args[i].getClass();
}
else {
parameterTypes[i] = null;
}
}
String methodName = joinPoint.getSignature().getName();
Method method = joinPoint.getSignature()
.getDeclaringType().getMethod(methodName, parameterTypes);
Class[]参数类型=新类[joinPoint.getArgs().length];
对象[]args=joinPoint.getArgs();
对于(inti=0;i你的方法没有错,但是有一个更好的方法。你必须向
您应该小心,因为Method Method=signature.getMethod()
将返回接口的方法,您应该添加此项以确保获得实现类的方法:
if (method.getDeclaringClass().isInterface()) {
try {
method= jointPoint.getTarget().getClass().getDeclaredMethod(jointPoint.getSignature().getName(),
method.getParameterTypes());
} catch (final SecurityException exception) {
//...
} catch (final NoSuchMethodException exception) {
//...
}
}
(catch中的代码为空,最好添加代码来管理异常)
如果您想要访问方法或参数注释(如果在spring boot应用程序中使用时,接口中不存在此注释),则可以使用此实现上述转换失败。然后,签名的类型为MethodSignatureImpl,它是spring MethodInvocationProceedingJoinPoint的私有内部类。更新到上述命令ent(这是错误的):在我的测试中,我导入了错误的MethodSignature类,这导致了ClassCastException。正确的类是org.aspectj.lang.reflect.MethodSignature。我如何做到这一点,而不是获取方法,而是获取方法所在的类?会MethodSignature#getDeclaringType()
这样做吗?但开发人员应该确定,joinpoint方法不是构造函数对吗?否则ClassCastException。如果我错了,请纠正我。如果可以的话,我会投票给你两次,一次投票给伟大的答案,一次投票给jointpoint
if (method.getDeclaringClass().isInterface()) {
try {
method= jointPoint.getTarget().getClass().getDeclaredMethod(jointPoint.getSignature().getName(),
method.getParameterTypes());
} catch (final SecurityException exception) {
//...
} catch (final NoSuchMethodException exception) {
//...
}
}