spring 从 ProceedingJoinPoint 获取 java.lang.reflect.Method?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5714411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting the java.lang.reflect.Method from a ProceedingJoinPoint?
提问by Erik
The question is short and simple: Is there a way to get the Method object from an apsectj ProceedingJoinPoint?
问题很简单:有没有办法从 apsectj ProceedingJoinPoint 获取 Method 对象?
Currently I am doing
目前我正在做
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);
but I don't think this is the way to go ...
但我不认为这是要走的路......
回答by Bozho
Your method is not wrong, but there's a better one. You have to cast to MethodSignature
你的方法没有错,但有更好的方法。你必须投射到MethodSignature
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
回答by Nordine
You should be careful because Method method = signature.getMethod()will return the method of the interface, you should add this to be sure to get the method of the implementation class:
你应该小心,因为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) {
//...
}
}
(The code in catch is voluntary empty, you better add code to manage the exception)
(catch中的代码是自愿为空的,最好加代码管理异常)
With this you'll have the implementation if you want to access method or parameter annotations if this one are not in the interface
有了这个,如果你想访问方法或参数注释,如果这个注释不在接口中,你将拥有实现

