简体   繁体   中英

Java classes are in the same package (different directories) but they can't access each other

I have two files:

MyProject/src/main/java/foo_package/bar_package/MainClass.java MyProject/src/gen/java/foo_package/bar_package/OtherClass.java

In both of those classes the very first line is:

package foo_package.bar_package;

If I call:

OtherClass foo = new OtherClass();

It cannot resolve symbol OtherClass. Why is that?

What I've tried:

  • Rebuild project
  • Invalidate cache/Restart
  • Reimport project
  • Delete .iml files and .idea folder and import everything again

It looks like there is a problem with the path of the last class:

MyProject/src/ main /java/foo_package/bar_package/MainClass.java MyProject/src/ gen /java/foo_package/bar_package/OtherClass.java

If your classes have the same package (package starts after ../java/ ) but they are not part of the java build path, then the IDE won't recognise them as valid.

Try moving your OtherClass.java to the package where the MainClass.java is. Doing this should eventually solve your problem.

PS: be aware about the source folders of your project (most of the time main is the source folder by default and it's enough but there may be other source folders, generally added manually).

Make sure that your IDEA source folder is java , not src (for both java folders inside /gen/ and inside /main ). The sources root is marked as a blue directory in "Project" window ( Alt + 1 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM