简体   繁体   English

在主类中使用包名称,导致NoClassFoundException

[英]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 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: 添加软件包Foo ,还应该更改文件夹结构:

 //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 ) (注意:您应该位于.目录,而不是./Foo

Check: http://docs.oracle.com/javase/tutorial/java/package/managingfiles.html 检查: 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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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