java - 如何通过反射获取多重签名调用方方法?

标签 java reflection

假设我们有:

@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/

相关文章:

Javascript 根据函数名调用函数

java - 发送带有两个方法的返回值的 JSON 响应

java - 需要匹配两个示例字符串的正则表达式

java - .class == getClass() 测试失败

c# - 反射(reflect)接口(interface)的所有属性,包括继承的属性?

java - 如何让 Java 反射(reflect)到父类(super class)中的点字段?不仅仅是实际的类(class)

Java 反射通用类型 ParamertizedType 对象创建失败并出现 java.lang.exception

java - 显示链接列表: Null Pointer Exception Error

java - GWT 中的 DataGrid,无法清除它

java - 关闭框架时保存目标文件