名称中带点的Java软件包文件夹 [英] Java package folders with a dot in the name
问题描述
根据规范,给定包含的 MyClass.java
文件
Is it by spec that, given a MyClass.java
file containing
package com.mycorp.foo;
public class MyClass {
public static void main (String[] args) {
System.out.println("Hello, world!");
}
}
在以下路径中(请注意文件夹名称中的点):
in the following path (note the dot in the folder name):
./com/mycorp.foo/MyClass.java
以下工作正常:
$ javac com/mycorp.foo/MyClass.java
产生 ./com/mycorp.foo/MyClass.class
,而这不起作用:
$ java com.mycorp.foo.MyClass
Exception in thread "main" java.lang.NoClassDefFoundError: com/mycorp/foo/MyClass
Caused by: java.lang.ClassNotFoundException: com.mycorp.foo.MyClass
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
推荐答案
在类文件顶部提到的打包结构与编译无关,而与有关,而与运行时有关,则更多.类加载.
-
您可以放入任何软件包名称并进行编译.例如以下Java类编译
You can put any packagename and compile it. e.g. following java class compiles
package com.sa.test.me.yes.no;
public class Test{
public static void main(String[] args){
System.out.println("Hello");
}
}
即使您没有放入与包声明相同的文件夹结构,它也会编译.您可以通过不放置任何文件夹进行测试(例如 java Test.java
)
It compiles even if you don't put inside a folder structure same as package declaration. You can test it by not putting in any folder (e.g java Test.java
)
2.在加载类时,包的组织更为重要.类加载器将始终根据包结构在文件夹中搜索类.因此,当您尝试运行程序时,类加载器会尝试根据包结构在文件夹中搜索类文件.
2 . Packages organization is more important while class loading. The classloader will always search for the class into the folder based on package structure. So when you are trying to run your program, the classloader tries to search for the class file in a folder as per the package structure.
这篇关于名称中带点的Java软件包文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!