0

I am looking in some legacy code in Scala and see a method:

private def method1 (value: AnyRef, fieldName: String, qualifiedFieldName: String, fieldType: Type, schema: Schema)
                         (implicit mode: ParseMode): Any = {...}

How to see who called (or who can call) this method (from where)? (tracking in IDE/InteliJ is fine - just want to 'track' who is calling a method in order to understand the code routes)..

Ideal print line right after a Method name (inside method body) would be:
This method is being called from this class etc...

stefanobaghino
  • 11,253
  • 4
  • 35
  • 63
user9750148
  • 375
  • 3
  • 5
  • 14
  • 1
    Have you think about throwing a fake exception and print the stack trace in a catch block ? It's kind of a hack but it should work. You can find the code snippet here : [Scala: print a stack trace in my Scalatra app](https://stackoverflow.com/questions/18880126/scala-print-a-stack-trace-in-my-scalatra-app) – Alex C. May 22 '18 at 13:09

1 Answers1

2

You can use Thread.currentThread.getStackTrace() to achieve that.

You can find more info on that on the official documentation.

It returns an Array[StackTraceElement], where each StackTraceElement holds the class, method, file name and line number of the caller, ordered from top to bottom of the call stack.

You can run the following method in the Scala shell to get a sense of the result:

def stackTraceInfo(thread: Thread): Seq[String] =
  thread.getStackTrace.map(ste => s"${ste.getClassName}.${ste.getMethodName}")

For example could yield something like the following:

scala> stackTraceInfo(Thread.currentThread).foreach(println)
java.lang.Thread.getStackTrace
$line7.$read$$iw$$iw$.stackTraceInfo
$line10.$read$$iw$$iw$.<init>
$line10.$read$$iw$$iw$.<clinit>
$line10.$eval$.$print$lzycompute
$line10.$eval$.$print
$line10.$eval.$print
...
stefanobaghino
  • 11,253
  • 4
  • 35
  • 63