1/29/2007

Why we have to use -jar option when running a self-contained jar

We can run a self-contained jar file with a command like this:

java -jar foo.jar
,where foo.jar contains a main class that is specified in META-INF/MANIFEST.MF with a Main-Class entry. What will happen if running if without -jar option? java will read foo.jar as a main class named jar in package foo:
C:\tmp>java foo.jar
Exception in thread "main" java.lang.NoClassDefFoundError: foo/jar
I guess that's the reason why -jar option is necessary to tell JVM to look for a jar file rather than a class file foo/jar.class. But realistically, how often people name their main class jar? Why can't we disallow this naming and then omit -jar option when running a jar file? JVM should be able to figure it out by .jar extension.

2 comments:

Binil said...

Good point. Both .jar and .class files are created by the JDK, so the VM need not force the user to specify it. Sun could change the meaning of -jar to mean that "the file does not have the .jar extension, but pretend its a jar".

Having said that, one reason why the VM might be the way it is would be that -jar flag might be specific to Sun VMs, and might not be available on other implementations. Is that so?

Steve Smith said...

Great and Useful Article.

Online Java Course

Java Online Training

Java Course Online

J2EE training

online J2EE training

Best Recommended books for Spring framework

Java Interview Questions












Java Training Institutes in Chennai

Java Training in Chennai

J2EE Training in Chennai

java j2ee training institutes in chennai