5

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

4

3 回答 3

5

这是一种实际上可以解决问题的方法:

val srcFile = new Exception().getStackTrace.head.getFileName
println(srcFile)

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

于 2015-05-18T15:35:42.287 回答
4

在 REPL 中,名称是控制台,但这表明一个位置知道它的来源。

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>
于 2015-05-18T22:53:55.433 回答
2

或者,你可以使用@li-haoyi 优秀的源码宏库

def foo(arg: String)(implicit file: sourcecode.File) = {
  println(s"this file is: '${file.getAbsolutePath}'")
}

foo("hello") // "this file is '/path/to/file'"

此外,还有许多其他好东西,例如行号、变量名称等。

于 2017-04-14T19:08:52.247 回答