简体   繁体   中英

using Package name in main Class, causes NoClassFoundException

My code:

//package Foo;
public class Bar{
public static void main(String[] argv){System.out.println("test");}
}

now, when i compile and runn it, the code will work but, when i uncomment the first line it will throw an exception when i try to run it with

java Bar

it will throw the following:

java.lang.NoClassDefFoundError: Bar (wrong name: Foo/Bar)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Exception in thread "main" 

And when i try to run it this way:

java Foo.Bar

i will get this:

Error: Could not find or load main class Foo.Bar

the same output will be generated when i do the Following:

java -classpath ./ Foo.Bar

even when i do specify the complete path to the current path , and i think it should not be neccesary but i did that, i still geht the message:" Could not find or load ...".

When you add package Foo , you should change also the folder structure:

 //before:
 ./Bar.java

 //after adding Foo package:
 ./Foo/Bar.java

Then you run it as follows:

./java Foo.Bar

(note: you should be in . directory, not ./Foo )

Check: http://docs.oracle.com/javase/tutorial/java/package/managingfiles.html

A quote from the link above:

  //in the Rectangle.java file package graphics; public class Rectangle { ... } 

Then, put the source file in a directory whose name reflects the name of the package to which the type belongs:

  .....\\graphics\\Rectangle.java 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM