Using Eclipse, when I write a 'hello world' test program the resulting executable jar is tiny despite rt.jar being on the build path. I would like to make a library-type jar that is added to the build path, but only contributes classes/code to the runnable jar if they are called/instantiated by the main application, as rt.jar seems to do.
-
Have you looked at what classpath does? – aksappy Nov 04 '16 at 11:32
-
Just using the ordinary Export Jar (rather than Runnable Jar) gives you the small 'library' jar. – greg-449 Nov 04 '16 at 11:47
1 Answers
I think you have a fundamental misunderstanding of how Java works. The Java compiler and JAR are not a "all-in-one" packaging tool, they don't include every possible class into your exported JAR.
When you build a JAR with Eclipse, it only includes the classes and resources from your project that you specify (by default, it includes them all). On the other hand, rt.jar
is part of the JRE distribution and is required for any Java program to run - it's part of the runtime. In other words, your little JAR would be useless without the machine it's running on having rt.jar
.
For example, let's say in your project you write the following classes:
MyApp
Person
Account
Each of those uses standard Java library classes like String
, Collection
, Thread
, etc, which are all present in rt.jar
When you export/build your JAR, it will contain only MyApp.class
, Person.class
, and Account.class
. It will not contain String.class
, Collection.class
, Thread.class
, or any other classes from rt.jar
(or from any other JAR that your project depends on).
Having said that, there are a few tools that try to build an "uber-JAR" (see What is a fat JAR?), but that's generally a special-need kind of thing, not how you would typically build JARs.