How to get current script or class name in Scala?

I would like my Scala program to be able to programmatically determine either its script file name or its class name, save the string in a variable programand print the name.

Java has several methods for this.

+2
source share
5 answers
// With help from huynhjl
// http://stackoverflow.com/questions/8129185#8131613

import scala.util.matching.Regex.MatchIterator

object ScriptName {
    val program = {
        val filenames = new RuntimeException("").getStackTrace.map { t => t.getFileName }
        val scala = filenames.indexOf("NativeMethodAccessorImpl.java")

        if (scala == -1)
            "<console>"
        else
            filenames(scala - 1)
    }

    def main(args: Array[String]) {
        val prog = program
        println("Program: " + prog)
    }
}

Rosetta code

+1
source

I think this is the simplest:

val program = new Exception().getStackTrace.head.getFileName
+3
source

, 0__, , , :

package utils

trait ProgramInfo {
  val programInfo = try { 
    throw new RuntimeException("x")
  } catch { 
    case e: RuntimeException =>
      val arr = new java.io.CharArrayWriter()
      val buffer = new java.io.PrintWriter(arr)
      e.printStackTrace(buffer)
      val trace = arr.toString 
      val lines = io.Source.fromString(trace)
      val pat = """^.*at.*\.main\(([^:]*)(:.*)?\).*$""".r
      lines.getLines().collectFirst{case pat(n, l) => n}.getOrElse("<none>")
  }
}

object ProgramInfo extends ProgramInfo

:

println(utils.ProgramInfo.programInfo)

object A extends utils.ProgramInfo {
   def main(args: Array[String]) {
     println(programInfo)
   }
}

This works for scripts scala A.scriptwhether the code is enclosed in an object or not. This also works when compiling with scalacand runs as scala A. When launched from REPL, this will return <none>.

+2
source

Not quite sure what you are looking for ...

$ scala -e 'println( "I am " + getClass.getName )'

gives me

"I am Main$$anon$1"

and

$ scala -e 'try { sys.error( "" )} catch { case e => println( "I am " + e.getStackTrace()( 3 ))}'

gives me

"I am Main.main(scalacmd2873893687624153305.scala)"
+1
source
#!/bin/bash
exec scala "$0" "$0" "$@"
!#

val program = args(0)
println(program)
-1
source

All Articles