0

My java project has 4 modules in directory project\src\x\y\z. A compile with maven or with javac -cp src\x\y\z src\x\y\z\*.java works (i.e. completes with no errors) and the timestamps indicate the class files were recreated, but javac -cp src\x\y\z src\x\y\z\MainClass.java fails with unable to find symbol errors where symbol is one of the other class names.

Attempting to run MainClass after a successful compile fails with cannot find MainClass error. (java -cp src\x\y\z src\x\y\z\MainClass)

Each module includes a package x.y.z; statement. If I move the java modules to another folder and remove the package statements compiles and execution are both successful.

What is going on and can it be fixed?

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
MikeL
  • 1
  • 1

1 Answers1

1

If the classes are in the package x.y.z then the directory that should be on your classpath needs to be src/, not src/x/y/z. The directories x/y/z are part of the structure that Java expects when searching for .class files in the package x.y.z and you must always point to the base of any directory tree containing .class files (i.e. so that the sub-directory matches what is expected by the package declaration).

Additionally if you want to run a class, you must specify the class name not a file name (i.e. x.y.z.MainClass and not x/y/z/MainClass.java). In fact java itself (i.e. the runtime, not the compiler) only cares about .java files when you run single-file programs, which is just a convenience feature for very simple code).

So java -cp src/ x.y.z.MainClass should run your code after javac src\x\y\z\*.java (the -cp here is wrong and unnecessary).

Ideally you would never have class files under src/ at all (since that's short for "source" and not "binary class files"):

Builds tend to put them under something like build/out/, bin/ or similar, but that's not required:

  • javac -d bin/ -cp bin/ src/x/y/z/*.java
  • javac -d bin/ -cp bin/ src/x/y/z/MainClass.java (maybe, optional after changing MainClass.java)
  • java -cp bin/ x.y.z.MainClass
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614