1

I have a jar file, for example foo.jar. My code contains a lot of libraries (almost 75 jar dependencies). I am not using anything like maven or gradle, I'm just using pure java with pure jar files as dependencies, and I am working on my project in IntelliJ Idea. I used the IDE's artifacts system to turn my code into foo.jar. All the jar dependencies are compressed into this jar file. I am barely using much code from any of the libraries, yet the whole library jar is in my final jar.

Is there a way to strip out everything from the jar that is not being used by the code? (Right now it weighs almost whole 2gbs)

Thanks!

1
  • Why not just rebuild? if you are leaving out more than you are keeping, that would be less "work" for the jar program anyway. If you are having issues with the Idea implementation, you can rebuild from the terminal with jar cf output-file input-files. This may or may not be the best path. It depends on how many libs you plan to keep.
    – Nate T
    Nov 4, 2021 at 23:16

1 Answer 1

3

This really is an engineering problem, a common way this is handles is keeping the libraries and your own application separate, and giving out updates to your program as partial updates, allowing people to keep the library jars.

In some cases, this is not possible,and a single jar needs to be used.

One of the tools you can use to remove non-linked files is Proguard, it has features for minification, obfuscation and optimizing.

Example: https://www.guardsquare.com/manual/configuration/examples#application

bin/proguard @myconfig.pro

File myconfig.pro

-injars       myapplication.jar
-outjars      myapplication_out.jar
-printmapping myapplication.map

-keep public class com.example.MyMain {
    public static void main(java.lang.String[]);
}

-optimizationpasses 3

Note that this is incompatible with the use of Reflection, as links to classes loaded with Reflection cannot be found, and are thus removed from the source code. Make sure to identify every of such spot and mark them using the keep option.

Another thing, if you run this directly on your libraries, it modifies the code of the libraries, which may or may not be allowed by their licenses

2
  • Doesn't it hinder decompiling as well? or am I thinking of something else? The name sounds familiar.
    – Nate T
    Nov 7, 2021 at 20:53
  • 1
    @NateT in its default config, it also changes class names (but keeps packages alone) This hinders decompilation. More aggresive options can be specified, which collapses all package names and removes all debugging options like line numbers and annotations (which also makes the final jar smaller)
    – Ferrybig
    Nov 7, 2021 at 21:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.