如何在Scala 2.11中查找封闭源文件的名称

Lui*_*gro 5 scala scala-2.11

在编译时,如何在scala 2.11中检索当前源文件的名称(代码编写的位置)?

Msh*_*nik 5

这是一种实际上有诀窍的有点hacky方式:

val srcFile = new Exception().getStackTrace.head.getFileName
println(srcFile)
Run Code Online (Sandbox Code Playgroud)

来源:如何在Scala中获取当前脚本或类名?


som*_*ytt 4

在 REPL 中,名称是 console,但这表明某个位置知道其来源。

scala> import scala.language.experimental.macros
import scala.language.experimental.macros

scala> import scala.reflect.macros.whitebox.Context
import scala.reflect.macros.whitebox.Context

scala> def f(c: Context): c.Tree = { import c._,universe._ ; Literal(Constant(c.enclosingPosition.source.file.name)) }
f: (c: scala.reflect.macros.whitebox.Context)c.Tree

scala> def g: String = macro f
defined term macro g: String

scala> g
res0: String = <console>
Run Code Online (Sandbox Code Playgroud)

  • `c.macroApplication.pos.source.file.name` (2认同)