Is it possible to recover the name of the function

2019-04-18 03:18发布

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.

2条回答
祖国的老花朵
2楼-- · 2019-04-18 03:33

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()
查看更多
祖国的老花朵
3楼-- · 2019-04-18 03:38
scala> def currentMethodName() : String = Thread.currentThread.getStackTrace()(2).getMethodName
currentMethodName: ()String

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

scala> getMeASammy()
getMeASammy
查看更多
登录 后发表回答