[英]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.我正在尝试从像 Eclipse 这样的 IDE 迁移到独立的 Java 环境,但是我在将多个文件绑定到一个项目中时遇到了问题。
Here is some sample code, where both files are in the same directory:这是一些示例代码,其中两个文件位于同一目录中:
App.java App.java
package com.example.main;
public class App {
public static void main(String[] args) {
Example.test();
}
}
Example.java例.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. 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:这是编译后执行
java App.java
时出现的错误:
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.如果您运行
App.java
11及以上, java App.java
If you need to refer Example.java
, first you need to compile both java files into a directory.如果您需要参考
Example.java
,首先您需要将两个 java 文件编译到一个目录中。 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
. java -cp classes com.example.main.App
。 Please note that App is without .class
suffix请注意,App 没有
.class
后缀
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.当然,如果项目变得更大或需要其他依赖项,建议使用Apache Maven或Gradle 之类的构建工具来构建您的项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.