How to find the name of the enclosing source file in Scala 2.11

ε祈祈猫儿з 提交于 2019-12-06 03:09:15

问题


At compile time, how to retrieve the name of the current source file (where the code is written) in scala 2.11?


回答1:


In the REPL, the name is console, but this shows that a position knows its source.

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>



回答2:


Here's a kinda hacky way that actually does the trick:

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

Source: How do I get the current script or class name in Scala?




回答3:


Or, you can use @li-haoyi's excellent sourcecode macro library

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

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

Plus, many other goodies like line number, variables names, etc.



来源:https://stackoverflow.com/questions/30306827/how-to-find-the-name-of-the-enclosing-source-file-in-scala-2-11

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!