[英]How to get the name of called method in java
假设我有一个这样的方法
Calculator calc;
public void testMethod(){
-----
----
Calc.add(1,2);
-----
-------
}
现在我要在函数末尾打印Calculator.add,即我想在函数末尾打印classname.printname。 打印应该足够通用,我也可以将其用于其他方法。 如何实现这个目标。
提前致谢
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();
}
作为最简单的方法,请记住,您始终可以调用this.getClass().getName()
:
class SimpleCalculator {
public int add(int a, int b) {
System.out.println(this.getClass().getName() +
" - adding " + a + " and " + b);
return a + b;
}
}
另一种常见的方法是使用Log4J之类的日志记录库。
您要使用的类是Logger
您将Log4J配置为写入特定文件。
每个类都声明一个Logger对象 ,该对象将消息打印到文件中。
每条消息均以生成该消息的类的名称开头。
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建议的方法。
...否则您可能会发疯并使用AOP 。
用户Calculator.getClass()。getName());用于查找类和Calculator.getMethod()的名称;
或使用System.out.println(“”我被“ + e.getStackTrace()[1] .getClassName()+”。“ + e.getStackTrace()[1] .getMethodName()+”()!调用!“ );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.