问题
Is there a way the file name of the current file (when the code is written) in scala?
Like my class is in a file like com/mysite/app/myclass.scala and i want to call a method that will return "myclass.scala" (or the full path...)
Thank you!
回答1:
This can be achieved with Scala macros, an experimental language feature available from version 2.10.
Macros make it possible to interact with the building of the AST during the source code parsing phase, and to modify trees of AST before the actual compilation is performed.
Since the information about the context of the compilation is available to the macro though the Context
object, during the parsing phase it is possible to retrieve the source file name and to return it as a String
literal, to be inserted in place of the macro call in the AST.
What follows is a working example of returning the source file name. The example is divided in two files:
A source file where the macro is defined and implemented:
// Contents of: "Macros.scala"
import scala.reflect.macros.Context
import scala.language.experimental.macros
object Macros {
def sourceFile: String = macro sourceFileImpl
def sourceFileImpl(c: Context) = {
import c.universe._
c.Expr[String](Literal(Constant(c.enclosingUnit.source.path.toString)))
}
}
Another source file where the macro is used:
// Contents of: "Main.scala"
object Main extends App {
val fileName = Macros.sourceFile
println(fileName)
}
The macro implementation and the code using it must be in different source files. The file name returned is the correct one, i.e. the name of the source file with macro call.
来源:https://stackoverflow.com/questions/21890028/get-filename-of-the-current-file-in-scala