I would like to know if it is possible to write an Ant task (using some other library if necessary) to reduce a JAR file so that it contains only certain classes and those on which they depend.
For example, I have a JAR containing classes A, B, C and D, where A and B both extend C. D is independent of the others. What I would like to do is specify to an Ant task that I only need class B, and end up with a JAR file that contains only B and C.
I have seen this answer which provides a simple way to say “I don’t want A and D”, and I imagine that replacing “excludes” with “includes” would allow me to specify “I do want B and C” like this:
<jar destfile="stripped.jar">
<zipfileset src="full.jar" includes="path/B.class;path/C.class"/>
</jar>
…but is there a dependency-aware way of doing this so that I can say “I want B” but end up with a JAR that contains B and its dependencies?
You could take a look at obfuscating tools, they can also often remove dead code, that is classes, methods and the like that are not referenced from anywhere in the code.
For example, you could use ProGuard.
From the documentation:
You can configure it to do just the shrinker step. In your case, you would use the
-keepoption to tellProGuardthat you want the B class, and end up with B and C as you describe. This might not be exactly what you want however sinceProGuardwill also remove unused methods and the like, modifying the classes in your JAR file (I do not know of any option to turn this off). Also, you need to tellProGuardnot to do any of the other stuff it normally does, such as obfuscation.If
ProGuarddoes not fit your needs, you can look for other obfuscation and/or shrinking tools. Hope this helps, and good luck!