Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Creating a small executable Jar relying on external Scala libraries

I'm trying to package a small application (still learning Scala!) in a "clean way". The goal is to have an executable JAR file. I've done the following:

  • packaged a JAR using sbt -> will work with
scala -cp myjarfile.jar MyClass

or

java -classpath path\to\scala-library.jar;myjarfile.jar MyClass

but won't work with

java -jar myjarfile.jar

because then scala/ScalaObject cannot be found. And no use adding a classpath on this last one, since the -jar option will ignore the -classpath option. Note that I have added the scala libs in my system CLASSPATH variable, but it seems to be ignored too when -jar is used.

  • added the scala library contents (by unzipping them first) to the jar created by sbt. This then works (the jar can be double-clicked and launched), but the manipulation is somewhat lengthy, and the resulting file is several megabytes big. Not ideal.

After hours of googling, I can see no way to create a small jar file that will launch when double-clicked and that doesn't involve a painful manipulation. What am I missing? I'm guessing there should be some way to define where the scala libraries are at system level. How do you deal with small applications that you want to be compiled and ready-to-run for efficiency?

Note that while I'm using sbt, I don't have a jar tool at hand (I'm relying on a JRE, not a JDK).

Thanks! Pierric.

like image 921
Pierric Avatar asked Apr 18 '11 16:04

Pierric


1 Answers

The following setup works for me:

  • have scala-library.jar in the same folder as the executable jar (and call java from there)
  • put this into your manifest: Class-Path: scala-library.jar

Another option is to merge the contents of scala-library.jar into your application jar. The drawback is that this will increase its size. But you can use Proguard to strip unused classes from your final jar. I think there is an easy way of using sbt to package an executable jar using proguard.

Regarding the shrinking using Proguard, you can have a look at this page. It's about Android development; just ignore this part and have a look at the tables of the shrinking results. Some example applications shrink to less than 100kB.

Edit

Maybe you need to refine your question a bit. What are you trying to achieve? Do you want to install the program only on your system or do you want to distribute it?

If all you want is quickly launching a Java application without much impact of the JVM start-up time you can have a look at nailgun.

like image 77
ziggystar Avatar answered Nov 15 '22 04:11

ziggystar