假设我们有:
@WebserviceUrl("/withObj")
public void caller(Object obj){
called();
}
@WebserviceUrl("/withoutObj")
public void caller(){
called();
}
如您所见,调用者有两个签名。为了获取堆栈跟踪,我们可以使用:
StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
但它只返回方法的名称。我怎样才能找到真正的来电者?
更新:
该问题的主要目的是读取方法注释中声明的 web 服务 url。错误检测调用方法,导致调用错误的webservice。
最佳答案
很有趣。我会想到的一种可能的方法是像人类一样做:读取堆栈跟踪中的行号,然后去上课。看起来像这样是可行的:How to get the line number of a method? .这不能直接应用,因为 CtClass.getDeclaredMethod
只给你一个方法签名。然而,你可以这样做:
String className;
String methodName;
int lineNumber;
// parse the stacktrace to get the name of the class, the name of the method and its line number
ClassPool pool = ClassPool.getDefault();
CtClass cc = pool.get(className);
CtMethod methodWhereExceptionOccurred =
Stream.of(cc.getDeclaredMethods())
.filter(method -> method.getName().equals(methodName))
.filter(method -> method.getMethodInfo().getLineNumber(0) == lineNumber)
.findFirst()
.get();
关于java - 如何通过反射获取多重签名调用方方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31625919/