【问题标题】:scala matchers works from jar not from sbtscala matchers 来自 jar 而不是来自 sbt
【发布时间】:2016-02-11 02:08:06
【问题描述】:

我有一个代码简介,它对 scala 类文件进行一些反思并寻找注释,类似于

// Create a new class loader with the directory
val cl = new URLClassLoader(allpaths.toArray)


getTypeNamesFromPath(sourceDir).map(s => {
  val cls = cl.loadClass(s)
  cls.getAnnotations.map(an =>
    an match {
      case q: javax.ws.rs.Path => println("found annotation")
      case _ => 
    })
})

此代码在 jar 中组装并使用 java -jar 运行时打印“找到的注释”,但从 sbt run 运行时不打印任何内容。

sbt 版本是 13.8, 斯卡拉版本 2.11.7

为了完整性

 private def getTypeNamesFromPath(file: File, currentPath: mutable.Stack[String] = new mutable.Stack[String]()): List[String] = {
    if (file.isDirectory) {
      var list = List[String]()
      for (f <- file.listFiles()) {
        currentPath.push(f.getName)
        list = list ++ getTypeNamesFromPath(f, currentPath)
      }
      return list
    }

    if (currentPath.isEmpty)
      throw new IllegalArgumentException(file.getAbsolutePath)

    currentPath.pop()

    if (file.getName.endsWith(".class")) {
      return List(currentPath.foldRight("")((s, b) => if (b.isEmpty) s else b + "." + s) + "." + file.getName.stripSuffix(".class"))
    }
    return List()
  }

【问题讨论】:

  • 什么是getTypeNamesFromPath(sourceDir)? sourceDir 实际上是源目录,还是包含.class 文件的目录?
  • sourceDir 是 ./target/scala_2.11/classes 文件夹的目录,getTypeNamesFromPath 只是一种从包文件夹结构中构造类型名称的方法,我发布了上面的方法

标签: java scala sbt


【解决方案1】:

所以事实证明我需要两件事......

  1. 使用来自scala.tools.nsc.util.ScalaClassLoader.URLClassLoader 的 URLClassLoader,这将解决加载正确的类的问题。

  2. 在 build.sbt 中设置 fork := true,因为一旦你执行步骤 #1,你会遇到类名冲突的问题,因为 sbt 使用自己的类路径和自己的类加载器版本运行,更多关于它这里http://www.scala-sbt.org/0.13.0/docs/Detailed-Topics/Forking.html

【讨论】:

    猜你喜欢
    • 2012-06-18
    • 2014-08-20
    • 2021-09-10
    • 2012-02-21
    • 1970-01-01
    • 1970-01-01
    • 2013-05-22
    • 1970-01-01
    • 2017-05-24
    相关资源
    最近更新 更多