简体   繁体   中英

Java file compile using javac unable to refer to other files in the same directory

I am trying to migrate from IDEs like Eclipse to a standalone Java environment, but I'm having problems tying together multiple files into a project.

Here is some sample code, where both files are in the same directory:

App.java

package com.example.main;

public class App {
    public static void main(String[] args) {
        Example.test();
    }
}

Example.java

package com.example.main;

public class Example {
    public static void test() {
        System.out.println("It's working");
    }
}

When running App.java in an IDE, the expected output of It's working is printed, however after executing javac *.java the files seem to ignore eachother.

Here is the error that occurs when executing java App.java after it's been compiled:

App.java:5: error: cannot find symbol
                Example.test();
                ^
  symbol:   variable Example
  location: class App
1 error
error: compilation failed

How can I compile the files in a project so that they recognise eachother?

If you running Java 11 and above, java App.java will compile App.java only.

If you need to refer Example.java , first you need to compile both java files into a directory. Let give it named 'classes'. The command will be

javac -d classes *.java

After that, you can run it via

java -cp classes com.example.main.App . Please note that App is without .class suffix

Of course, it is advisable to use build tools like Apache Maven or Gradle to build your project if it grow larger or need other dependencies.

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