java包:找不到符号 [英] java packages: cannot find symbol
问题描述
我有一个奇怪的错误。我在同一个包中有2个类,但他们找不到对方。从我记忆中来看,只要这些类在同一个包中,它们就应该能够调用彼此的方法。
我的代码与此类似:
在A.java中:
package com.mypackage;
公共类A {
public static int read(){
// some code
}
}
:
package com.mypackage;
公共类B {
public static void main(String args []){
int x = A.read();
}
}
它给了我一个
找不到符号变量A
错误。
这两个类都取决于某些
.jar
文件,但我已经将这些jar的路径包含到CLASSPATH
和A.java
编译好了,但是B由于某些原因找不到A ...
当我删除
包com.mypackage;
时两个类然后他们编译好。解决方案由于您正在编译不同包中的Java文件,因此您必须确保它们编译为适当的目录。
您可以使用此调用来执行此操作。用源文件的位置替换
$ SRC
,你可以让$ BIN
成为当前目录,或者一些您计算机上的其他位置。javac -sourcepath $ SRC -d $ BIN A.java B.java
当你想要运行它们时,你必须再次手动将它们添加到类路径中(但这不是一件坏事) 。
java -cp $ BIN com.mypackage.B
此调用应该有效;只是确定了A.java和B.java驻留在我的桌面上。使用
-d
标志,确保在编译时,它们转到相应的包文件夹方案。I'm having a strange error. I have 2 classes in the same package but they can't find each other. From what I remember, as long as the classes are in the same package, they should be able to call each other's methods.
My code looks similar to this:
in A.java:
package com.mypackage; public class A{ public static int read(){ //some code } }
in B.java:
package com.mypackage; public class B{ public static void main(String args[]){ int x = A.read(); } }
and it's giving me a
cannot find symbol variable A
error.Both of these classes depend on some
.jar
files, but I've already included the path of those jars toCLASSPATH
andA.java
compiled fine, but B can't find A for some reasons...When I remove the
package com.mypackage;
in both classes then they compile fine.解决方案Since you're compiling Java files that are in distinct packages, you'll have to ensure that they compile to the appropriate directories.
You can use this invocation to do just that. Substitute
$SRC
with the location of your source files, and you can let$BIN
be the current directory, or some other location on your machine.javac -sourcepath $SRC -d $BIN A.java B.java
When you want to run them, you have to add them manually to the classpath again (but that's not such a bad thing).
java -cp $BIN com.mypackage.B
This invocation should work; just made sure of it with A.java and B.java residing on my desktop. With the
-d
flag, that ensured that when they compiled, they went to the appropriate package folder scheme.这篇关于java包:找不到符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!