Java的方法可以“知道”自己的名字吗?

时间:2012-09-11 00:48:30

标签: java

  

可能重复:
  Getting the name of the current executing method

Java中是否有办法让某个方法知道自己的名字?如果是这样,如何从方法内部引用它?

2 个答案:

答案 0 :(得分:5)

您可以通过分析堆栈跟踪来确定它。但它可能会带来相当大的性能损失。在AOP Universe中,您还可以使用方面来确定方法名称并将其存储在某种上下文中。

在堆栈跟踪方法中,您可以执行类似

的操作
Exception e = new Exception();
e.fillInStackTrace();
e.getStackTrace()[0].getMethodName();

或(如评论中所示)

Thread.currentThread().getStackTrace()[0].getMethodName();

答案 1 :(得分:4)

堆栈跟踪的第一个元素(Thread.currentThread().getStackTrace(),请参阅this question)应告诉您当前在运行时的方法。

相关问题