2

我想做一个宏,在编译时验证其他项目中资源的存在。是否可以从上下文中获取此信息?

  def example_impl(c: Context): c.Expr[Unit] = {
    import c.universe._
    //instead of  
    // val r = this.getClass().getResource("/file.txt")

    val r = c.somthing.getResource("/file.txt")
    //...
  }

这可能是不可能的。但如果是的话,我想知道该怎么做。

4

2 回答 2

1

让我们首先考虑什么是“资源”。资源是可以从类路径中的目录开始找到的文件。请注意,为此目的,jar 文件是一个目录,因为它存储一个 zip 文件系统。类路径是运行 Java 时可用的环境信息。

还有一个根本问题:Scala 编译器不知道这些资源在哪里!它接收要编译的源文件,可能是目标目录,并且它有自己的类路径,但它们与运行 scalac 相关,而不是与 scalac 正在编译的代码有关。

“生成”资源的不是编译器——scalac 和 javac 都不是。它是其他工具,例如jar(命令行工具),通常由其他工具调用,例如构建系统(ant、maven、sbt)。

因此,没有关于在哪里可以找到这些资源的信息——它们通常位于与源代码分开的目录中。您可以使用普通的 Scala 文件 i/o 支持来遍历目录等,但是在编译时没有可用的“资源源”信息。

于 2013-12-11T19:03:44.590 回答
1

I did eventually get this working with Context.classpath.

https://github.com/marklemay/sacala-validation-macros/blob/master/macroHost2/src/main/scala/macroHost/Macros.scala

However I have only tested it within the scala IDE (eclipse). It would have to be tested it in sbt, intelij, maven and scalac before I was confident with it.

于 2015-04-26T14:44:29.580 回答