java packages: cannot find symbol

狂风中的少年 提交于 2019-12-17 16:32:06

问题


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 to CLASSPATH and A.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.


回答1:


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.




回答2:


It should be:

A.java

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

B.java

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


来源:https://stackoverflow.com/questions/11527941/java-packages-cannot-find-symbol

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!