javacommand-linepackagejavac

Compiling multiple packages using the command line in Java with external Jars


I have the following file structure that I need to compile using the command line. I have been using Eclipse all this while and it works fine in the editor.

/src
     /maps
          Structures/ (.java files) using a 3rd party external JAR file in E:\Lib\math.jar
          Util/ (.java files)
          TestClasses/ (.java files) Test.java is the main class

I compiled the above files using the following javac directive

C:\src\maps>javac -classpath E:\Lib\math.jar Util\*.java Structures\*.java TestClasses\*.java

This compiles without a problem and creates the relevant .class files.

However, when I try to run the main class using the following java directive

C:\src\maps>java TestClasses\TestSOM

I get the following exception

Exception in thread "main" java.lang.NoClassDefFoundError: TestClasses\TestSOM (
wrong name: maps/TestClasses/TestSOM)
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:791)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:14
2)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
        at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
        at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:472)

what is the correct way of executing the main class using the command line?


Solution

  • Use the fully qualified name of the class AND include the libraries as well to avoid the runtime errors for the classes referenced

    C:\src\>java -classpath .;E:\Lib\math.jar map.TestClasses.Test
    

    Assuming that Test.java has main method as you mentioned.