I want to export part of a Java project into a jar file while only including the class files that are necessary to run the main class. The project contains other main classes with similar but not identical dependencies. I can run a custom script to achieve it, like this:
mkdir temp
cd temp
javac -sourcepath "../" -d . ../MAINCLASS_A.java
jar cmf MAINCLASS_A.manifest ../MAINCLASS_A.jar *
For elegance and to more easily share with others I'd like to run it directly from Eclipse instead of this custom script. However, when I Export into a JAR file, or a Runnable JAR file, every class file in the project is included. I know I can set up manual filters to exclud开发者_如何学运维e certain files, but it seems there should be a smarter option. How can I configure Eclipse to only include the class files that the main class actually depends on?
I think that what you want to do is impossible in general case. Yes, theoretically javac can find (and finds) all dependencies between classes. But it is correct only if these dependencies are hard coded within your project, i.e. you do not use any dynamic class loading and reflection either directly or indirectly.
Real applications typically use various third party libraries, frameworks etc. So, sometimes dynamic class loading is used even if you never say in your own code Class.forName()
. I think that if you need such kind of optimization you have to write your custom script that builds your custom jar. BTW the fact that you need it probably gives you a tip that your projects are organized incorrectly. You should probably separate your project into 2 or more. Each one should contain only its dependencies. In this case you can use the built in eclipse ability to package jar files.
You can't do that. All the classes on which your main class depends on will not be known until runtime.
Say, we're loading a class using Class.forName("com.foo.Bar")
. In this case, the only reference to com.foo.Bar
inside the main class is the string literal, which will not be loaded by javac
or jar
.
Thus, your only option is to set up manual filters, save the .jardesc
file and use it as a script to create similar Jar files later on.
This should give you a head start.
http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Ftasks%2Ftasks-33.htm
精彩评论