Search code examples
javagradledirectorynoclassdeffounderror

Java.lang.NoClassDefFoundError wrong name: how to solve this?


I have created a very simple Java application, and built it using Gradle.

It is an application with just the Standard "Hello World" Java class (shown below).

I have built it with Gradle successfully and my .class file has been created at the standard folder location:

build>classes>main>my>package>HelloWorld.class

However, when I navigate to this folder and run in cmd line:

java HelloWorld

I get the following error:

Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld (wrong name: my/package/HelloWorld)
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
        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:425)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
        at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:482)

My HelloWorld.java

package my.package;

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

What is the cause of this error?


Solution

  • You should run the command (in Windows)

    java my\package\HelloWorld
    

    from the directory build/classes/main and not from build/classes/main/my/package. This is because HelloWorld class declares that it resides in the package my.package with package my.package;.