Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JVM Can't Find My Class: java.lang.NoClassDefFoundError

Tags:

java

My directory structure looks like this.

PackagesUnit3/com/myname/start/PackagesTest.java
(this class contains my main and the import statement "import com.systems.mui.*;)

PackagesUnit3/com/systems/mui/Test.java
(this class contains the package statement "package com.systems.mui;")

With PackageUnit3 as my base directory I can compile both classes successfully with the statement

"javac com/myname/start/PackagesTest.java"

However I cannot run the code with the command

"java com.myname.start.PackagesTest"

Error: "Exception in thread "main" java.lang.NoClassDefFoundError: com/myname/start/PackagesTest (wrong name: PackagesTest)"

The complier successfully generated .class files for each of the java classes and placed them in the same location as the source files.

According to Horstmann, "Core Java" 9th ed. p. 186, my "java" command syntax ought to work.

I should not have to specify the current directory (".")because I am not using the classpath (-cp) option.

One note: I used the "SUBST R: " command to establish the PackagesUnit3 directory as the base directory. My actual command line looks like R:>

Any suggestions??

like image 452
Garrett A. Hughes Avatar asked Aug 02 '13 14:08

Garrett A. Hughes


1 Answers

Given the exception, it looks like you're missing a package statement:

package com.myname.start;

Your package declaration should match your directory structure, and then the class will be generated with the correct fully-qualified name of com.myname.start.PackageTest.

Either compile in an IDE which will sort things out for you, or compile from the root of your package structure with an optional -d argument to specify the root output directory, e.g.

$ javac -d bin com/myname/start/*.java
$ java -cp bin com.myname.start.PackageTest
like image 53
Jon Skeet Avatar answered Nov 07 '22 15:11

Jon Skeet