views:

116

answers:

2

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.

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

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

scala> getMeASammy()
getMeASammy
Richard Fearn
+2  A: 

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()
Dave Griffith