java java包:找不到符号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11527941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 05:27:11  来源:igfitidea点击:

java packages: cannot find symbol

javapackages

提问by Dao Lam

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.

我有一个奇怪的错误。我在同一个包中有 2 个类,但它们找不到彼此。据我所知,只要类在同一个包中,它们应该可以调用彼此的方法。

My code looks similar to this:

我的代码看起来类似于:

in A.java:

在 A.java 中:

package com.mypackage;
public class A{
   public static int read(){
    //some code
   }
}

in B.java:

在 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 Aerror.

它给了我一个cannot find symbol variable A错误。

Both of these classes depend on some .jarfiles, but I've already included the path of those jars to CLASSPATHand A.javacompiled fine, but B can't find A for some reasons...

这两个类都依赖于一些.jar文件,但我已经包含了这些 jars 的路径CLASSPATHA.java编译得很好,但是 B 由于某些原因找不到 A...

When I remove the package com.mypackage;in both classes then they compile fine.

当我删除package com.mypackage;两个类中的 时,它们编译得很好。

采纳答案by Makoto

Since you're compiling Java files that are in distinct packages, you'll have to ensure that they compile to the appropriate directories.

由于您正在编译位于不同包中的 Java 文件,因此您必须确保它们编译到适当的目录中。

You can use this invocation to do just that. Substitute $SRCwith the location of your source files, and you can let $BINbe the current directory, or some other location on your machine.

您可以使用此调用来做到这一点。替换$SRC为源文件的位置,您可以将$BIN其设为当前目录或计算机上的其他位置。

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 -dflag, that ensured that when they compiled, they went to the appropriate package folder scheme.

这个调用应该有效;只是确保它与 A.java 和 B.java 驻留在我的桌面上。使用该-d标志,可确保在编译时进入适当的包文件夹方案。

回答by Jyro117

It should be:

它应该是:

A.java

一个.java

package com.mypackage;
class A {
    public static int read(){
       //some code
    }
}

B.java

B.java

package com.mypackage;
class B {
    public static void main(String args[]){
       int x = A.read();
    }
}