how to add tools.jar as a “dynamic dependency” in sbt. is it possible?

限于喜欢 提交于 2019-12-05 02:17:04

问题


i need to use tools.jar in my project, but there is not much sense to package it in the jar, since the user already have it. so, is it possible to use it as a "dynamic dependency"? meaning, i want my code to compile by using tools.jar file found in my JAVA_HOME, but i don't want it to get packaged with it. i can make sure to add it to the classpath with double activation at runtime with the user's JAVA_HOME used instead. for example:

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
}

FYI: i packge the app using assembly plugin in a standalone jar file.

EDIT:

an ugly solution would be to copy the tools.jar file to a lib directory in my project, and add:

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

in build.sbt can it be done more elegantly, without copying the jar file? would be much more easier to switch JVMs, and use the "right" tools.jar file automatically...


回答1:


after reading more carefully the SBT Documentation, i found out how to do this:
in build.sbt i needed to add:

// 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"}
}

and that's about it... simple as that :)




回答2:


There is an sbt plugin to do this for you now: https://github.com/chipsenkbeil/sbt-jdi-tools




回答3:


I haven't tested this, but could you not use the % configuration syntax to only map the dependency into runtime or compile? surely tools.jar should be automatically included anyway?

libraryDependencies += "com.sun" % "tools" % "1.6.0" % system

I'm not sure about the "system" configuration, I know this works in maven, you could try this with "compile" instead though.



来源:https://stackoverflow.com/questions/12409847/how-to-add-tools-jar-as-a-dynamic-dependency-in-sbt-is-it-possible

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