Is it possible to recover the name of the function

2019-04-18 03:05发布

问题:

I'd like to do something like

def getMeASammy() {println "getMeASammy"}
def getMeADrink() {println "getMeADrink"}
def getMeASub() {println "getMeASub"}

But, I don't want to explicitly type out the name of the function.

回答1:

scala> def currentMethodName() : String = Thread.currentThread.getStackTrace()(2).getMethodName
currentMethodName: ()String

scala> def getMeASammy() = { println(currentMethodName()) }
getMeASammy: ()Unit

scala> getMeASammy()
getMeASammy


回答2:

It's somewhat revolting, but the only supported way to get the name of the current method from the JVM is to create an exception (but not throw it), and then read the method name out of the exception's stack trace.

  def methodName:String= new Exception().getStackTrace().apply(1).getMethodName()