scala - 如何将tools.jar添加为sbt中的 "dynamic dependency"。是否可以?

标签 scala dependencies sbt tools.jar

我需要在我的项目中使用tools.jar,但是将其打包在jar中没有多大意义,因为用户已经拥有它。那么,是否可以将其用作“动态依赖项”?意思是,我希望我的代码使用 my JAVA_HOME 中找到的 tools.jar 文件来编译,但我不这样做不希望它与它一起打包。我可以确保将其添加到类路径中,并在运行时使用用户的 JAVA_HOME 进行双重激活。例如:

object Main1 extends App {
    val myjar = Main1.getClass.getProtectionDomain.getCodeSource.getLocation.getFile
    val tools = System.getProperty("java.home").dropRight(3)+"lib/tools.jar" // drop "jre"
    val arguments = Array("java", "-cp", myjar+":"+tools, "me.myapp.Main2") ++ args
    val p = Runtime.getRuntime.exec(arguments)
    p.getErrorStream.close
    p.getOutputStream.close
}

仅供引用:我使用程序集插件将应用程序打包在独立的 jar 文件中。

编辑:

一个丑陋的解决方案是将 tools.jar 文件复制到我的项目中的 lib 目录,并添加:

excludedJars in assembly <<= (fullClasspath in assembly) map { cp => 
    cp filter {_.data.getName == "tools.jar"}
}

build.sbt中 是否可以更优雅地完成而不复制 jar 文件?切换 JVM 会更容易,并自动使用“正确的”tools.jar 文件...

最佳答案

仔细阅读 SBT Documentation 后,我找到了如何做到这一点:
build.sbt 中我需要添加:

// adding the tools.jar to the unmanaged-jars seq
unmanagedJars in Compile ~= {uj => 
    Seq(Attributed.blank(file(System.getProperty("java.home").dropRight(3)+"lib/tools.jar"))) ++ uj
}

// exluding the tools.jar file from the build
excludedJars in assembly <<= (fullClasspath in assembly) map { cp => 
    cp filter {_.data.getName == "tools.jar"}
}

就是这样......就这么简单:)

关于scala - 如何将tools.jar添加为sbt中的 "dynamic dependency"。是否可以?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12409847/

相关文章:

scala - Spark本地测试报OutOfMemoryError,如何解决?

performance - 慢 Scala 断言

java - 创建不包含外部依赖项的 JAR 文件

c# - 应用程序启动失败,因为它的并行配置不正确

scala - Scala 中什么时候需要 @uncheckedVariance?为什么在 GenericTraversableTemplate 中使用它?

scala - 为什么 Scala for 循环比逻辑上相同的 while 循环慢?

java - android类构造函数中的最佳实践

scala - 如何在不同机器上重用已编译的源代码

unit-testing - sbt testOnly 不工作

scala - SBT 远程调试在 intellij 中有效,但在执行测试时无效