Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out which Java classes are actually loaded and reduce jar

Tags:

java

maven

Is there a way to automatically find out which Java classes are actually loaded (either during compile time, as far as that's possible, or during the runtime of an application), and to throw out all other classes from a JAR to create a smaller JAR? Does that actually make sense in practice?

I am talking about the application classes for an application JAR. Usually there are lots of libraries in an application, and an application rarely needs all features of those libraries. So I suspect that would make a considerably smaller application. In theory that might be done for example via an Java agent that logs which classes and resources are read by one or several runs of an application (or even just by java -verbose:class), and a maven plugin that throws out all other classes from a jar-with-dependencies. Is there already something like that?

Clarification: I am not talking about unused dependencies (JARs that are not used at all), but about removing unused parts of each included JAR.

like image 578
Hans-Peter Störr Avatar asked Nov 06 '18 08:11

Hans-Peter Störr


People also ask

How can you tell which class a jar is loaded?

Use –verbose:class flag with your java command line. This option enables loading and unloading of classes. It shows the jar file from which the class is loaded.

What classes are in jar?

The JAR file contains the TicTacToe class file and the audio and images directory, as expected. The output also shows that the JAR file contains a default manifest file, META-INF/MANIFEST. MF, which was automatically placed in the archive by the JAR tool.

How do I reduce the size of a class in Java?

Use an obfuscator like ProGuard, JoGa, or JShrink to optimize the size of your class. Use a single character for the class file name. This reduces its size internally, reduces the amount of info the Zip program stores, and reduces the size of the manifest. Reference as few classes as possible.


1 Answers

Well, the Maven Shade Plugin has an option minimizeJar when creating an Uber-JAR for your application:

https://maven.apache.org/plugins/maven-shade-plugin/

But, as others already pointed out, this is quite dangerous, as it regularly fails to detect class accesses which are done via Reflection or other dynamic references.

like image 63
Florian Albrecht Avatar answered Oct 11 '22 12:10

Florian Albrecht