Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
155 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...