norlesh
norlesh

Reputation: 1861

NoClassDefFoundError thrown when specifying same jar file at compile and run time

Hi I'm trying to use an external Java package from my own code and keep getting NoClassDefFoundError even though I am using the same class path that I compiled with.

For your amusement I have included a bare bones reproduction of what will undoubtedly be a dumb mistake on my part (I've been at this for about 6 hours so far)

/* WTF/WTF.java */  
import foo.Bar;  
class WTF  
{
    public static void main(String[] args)  
    {  
        Bar dontCare = new Bar();  
    }
}  

/* WTF/foo/Bar.java */  
package foo;  

class Bar  
{  
    public Bar() {}  
}  

Now from the WTF directory I run the following:

javac foo/Bar.java              [ok]  
javac WTF.java                  [ok]  
java WTF                        [ok]  
jar cf foo.jar foo              [ok]  

I remove the WTF/foo directory so there is only WTF/foo.jar available.

javac WTF.java -cp foo.jar      [ok]  
java WTF -cp foo.jar            [$!@#$!]  
Exception in thread "main" java.lang.NoClassDefFoundError: foo/Bar
    at WTF.main(WTF.java:7)
Caused by: java.lang.ClassNotFoundException: foo.Bar
    at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:266)

Any clues greatly appreciated!

Upvotes: 1

Views: 1428

Answers (2)

Kru
Kru

Reputation: 4235

The directory where is WTF.class should be in the classpath. Also, Bar should be public.

java -cp foo.jar:. WTF

: is the path separator in Linux, if you are using Windows replace it with ;.

Upvotes: 1

Koziołek
Koziołek

Reputation: 2874

Wrong arguments sequence? Try:

java -cp foo.jar WTF

Upvotes: 1

Related Questions