8

Today I learned:

In Java, you're supposed to compile a source file in its package one directory up, outside of its package. You can't compile the source file in its own package directory, for it will state "cannot find symbol" on files in the same package, even though they're in the correct package directory. That can be quite confusing at first.

Given the following directory structure:

|_
|_ \pkg
|_ _ Src1.java
|_ _ Src2.java (interface with static method)

and the following source:

package pkg;
public interface Src2 { static void doStuff() { ... }; } // assuming JDK8+, where static default methods are allowed

package pkg;
public class Src1 { public static void main(String[] args) { Src2.doStuff(); } }

..being inside the pkg/ directory in the console,

this won't work:
javac -cp . Src1.java

"cannot find symbol: Src2"

However, go one directory up and..

javac -cp pkg/*.java pkg/Src1.java

..it works!

Yeah, you truly start learning how the compiler works when you don't use the luxury of a IDE but rather a raw text editor and a console.

Comments
  • 1
    This is not (entirely) correct.

    https://docs.oracle.com/javase/8/...

    You've mixed up directories vs files vs Bash / Variable substitution.

    Be very careful with CLI command line arguments and wildcard characters, as most of the time it might do what you expect except it does not work the way you'd think it does.

    Dot / . is a relative path. It can be evaluated inside the CLI, but it's up to the CLI to decide what it means.

    https://github.com/AdoptOpenJDK/...

    Look up the source code. What happens really?
Add Comment