最近为了考试开始学习Java。
在学习包时,尝试了这个并收到错误消息。我所做的是
//Creating class A (Within package the package: com.test.helpers)
package com.test.helpers;
public class A {
public void sayHello(){
System.out.println("Hello World");
}
}
//And then the class App utilising the class A
import com.test.helpers.*;
public class App{
public static void main(String args[]){
A a = new A();
a.sayHello();
}
}
我将这两个文件都放在名为“JavaTest”的目录中(在 Windows 7 上),并首先使用命令编译 A.java javac -d . A.java
然后,在尝试编译 App.java 时,我收到以下错误消息:
App.java:5: error: cannot access A
A a = new A();
^
bad source file: .\A.java
file does not contain class A
Please remove or make sure it appears in the correct subdirectory of the source path.
1 error
但是,问题似乎可以通过两种方式解决,
- 删除源文件 A.java
- 在文件
App.java
中将导入语句从import com.test.helpers.*;
更改为import com.test.helpers.A
。
如果您能解释这里发生的事情,我将不胜感激。或者我可能犯了一个愚蠢的人为错误或语法错误。
原文由 user3210872 发布,翻译遵循 CC BY-SA 4.0 许可协议
您好,这里的问题是 JVM 混淆了类文件,因为
ambiguous
两个目录中的类文件名(JavaTest
以及com.test.helpers
目录).当你做
javac -d . A.java
编译器在目录com.test.helpers
中生成一个类文件 --- 现在它将它与JavaTest
中的源文件混淆Deleting the Source file A.java
当您从
JavaTest
中删除源文件A.java
--- 时,JVM 现在知道com.test....
-- 中的类文件将被使用。Changing the import statement from 'import com.test.helpers.*;' to 'import com.test.helpers.A' in the file, 'App.java'.
在这里,您指定要在类实现中使用的特定文件,即您告诉编译器使用文件
A.java
来自com.test...
而不是来自JavaTest
现在,这种歧义的解决方案对你来说永远不是问题,你必须使用导入语句导入特定文件,即
import com.test.helpers.A;
或者如果你想做import com.test.helpers.*;
那么你必须特别使用com.test.helpers.A
代替A
在当前类实现的任何地方告诉编译器不要将它与JavaTest
的源代码混淆我知道这个特定的答案已经晚了很多,但我想为即将到来的读者分享我的观点,如果它能以任何方式帮助他们,那就太好了。谢谢!