java中如何获取被调用方法的名称
假设我有一个这样的方法java中如何获取被调用方法的名称,java,logging,reflection,Java,Logging,Reflection,假设我有一个这样的方法 Calculator calc; public void testMethod(){ ----- ---- Calc.add(1,2); ----- ------- } 现在我想在函数末尾打印Calculator.add,也就是说,我想在函数末尾打印classname.printname。打印应该足够通用,我可以使用其他方法以及相同的。如何实现这一目标 提前感谢作为最简单的方法,请记住您可以随时调用this.getClass().getName(): private s
Calculator calc;
public void testMethod(){
-----
----
Calc.add(1,2);
-----
-------
}
现在我想在函数末尾打印Calculator.add,也就是说,我想在函数末尾打印classname.printname。打印应该足够通用,我可以使用其他方法以及相同的。如何实现这一目标
提前感谢作为最简单的方法,请记住您可以随时调用
this.getClass().getName()
:
private static final int CLIENT_CODE_STACK_INDEX;
static {
// Finds out the index of "this code" in the returned stack trace - funny but it differs in JDK 1.5 and 1.6
int i = 0;
for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
i++;
if (ste.getClassName().equals(Resource.class.getName())) {
break;
}
}
CLIENT_CODE_STACK_INDEX = i;
}
public static String getCurrentMethodName() {
return Thread.currentThread().getStackTrace()[CLIENT_CODE_STACK_INDEX].getMethodName();
}
public static String getCallerMethodName() {
return Thread.currentThread().getStackTrace()[CLIENT_CODE_STACK_INDEX+1].getMethodName();
}
另一种常见的方法是使用日志库,如
class SimpleCalculator {
Logger calcLogger = Logger.getLogger(SimpleCalculator.class);
public int add(int a, int b) {
calcLogger.debug("add - adding " + a + " and " + b);
return a + b;
}
}
。。。或者你可以使用@urir建议的方法
。。。或者您可能会发疯并使用。作为最简单的方法,请记住您始终可以调用
this.getClass().getName()
:
另一种常见的方法是使用日志库,如
class SimpleCalculator {
Logger calcLogger = Logger.getLogger(SimpleCalculator.class);
public int add(int a, int b) {
calcLogger.debug("add - adding " + a + " and " + b);
return a + b;
}
}
。。。或者你可以使用@urir建议的方法
。。。或者你可能会发疯并使用。用户计算器.getClass().getName());用于查找类和计算器的名称。getMethod()
或者使用System.out.println(“我被“+e.getStackTrace()[1].getClassName()+
"." +
e、 getStackTrace()[1]。getMethodName()+
"()!" ); 用户计算器.getClass().getName());用于查找类和计算器的名称。getMethod()
或者使用System.out.println(“我被“+e.getStackTrace()[1].getClassName()+
"." +
e、 getStackTrace()[1]。getMethodName()+
"()!" ); 我不太明白,你想打印你正在使用的方法还是刚刚调用的方法?Calc应该以小写字母c开头吗?@berry我刚才调用的方法在哪里进行打印?您正在尝试写入日志文件吗?如果是这样,请查看Log4J。这是一个java日志库。我不太明白,你想打印你所使用的方法还是刚刚调用的方法?Calc应该以小写字母c开头吗?@berry我刚才调用的方法在哪里进行打印?您正在尝试写入日志文件吗?如果是这样,请查看Log4J。它是一个用于java.im在线程“main”java.lang.ArrayIndexOutOfBoundsException中获取异常的日志库:数组索引超出范围:6在反射处。getCallerMethodName(Reflections.java:32)在反射处。main(Reflections.java:41)可能是因为“main”在线程“main”中没有“caller”im获取异常java.lang.ArrayIndexOutOfBoundsException:数组索引超出范围:6在Reflections.getCallerMethodName(Reflections.java:32)在Reflections.main(Reflections.java:41)可能是因为“main”没有“caller”,我无法编辑我调用的方法。我应该能够通过调用该方法的方法实现此目标。我无法编辑我调用的方法。我应该能够通过调用该方法的方法实现这个目标。