Michael Lee Michael Lee - 3 years ago 104
Linux Question

How to set environment variable CLASSPATH and NoClassDefFoundError on LINUX

I've been studying classpaths and came across a question.
I used the code below:

class AAA
public AAA()
class BBB
public BBB()
class ABMain
public static void main(String[] args)
AAA aaa=new AAA();
BBB bbb=new BBB();

On terminal, I did:

  1. javac ABMain.java

  2. mkdir sub

  3. set CLASSPATH=.:.\sub;

  4. move AAA.class .\sub\AAA.class

  5. move BBB.class .\sub\BBB.class

  6. java ABMain

When I checked the sub directory, I found that AAA.class and BBB.class were correctly moved, but when I try to run ABMain, I get the following:

Exception in thread "main" java.lang.NoClassDefFoundError: AAA
at ABMain.main(ABMain.java:17)
Caused by: java.lang.ClassNotFoundException: AAA
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more

Could you please comment on what I should change to make it work? Thank you in advance.

Answer Source

According to title, you use LINUX. But your steps are for windows ecosystem. To correct the example, you should use direct slash as path delimiter, and add current dir as CLASSPATH alternative (to be able to load main class as well):

  1. javac ABMain.java
  2. mv AAA.class ./sub/AAA.class
  3. mv BBB.class ./sub/BBB.class
  4. java -cp ./sub:. ABMain
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download