简体   繁体   English

在同一 package 中编译两个 java 文件时出现编译错误

[英]Compiling error while compiling two java files in the same package that use each other

Suppose we have two.java files in the same directory.假设我们在同一个目录下有两个.java文件。

Test.java:测试.java:

public class Test {
    public void func() {
        System.out.println("Hello World");
    }
}

Main.java:主要.java:

public class Main {
    public static void main(String args[]) {
        Test t = new Test();
        t.func();
    }
}

If I write in the command line: javac Main.java如果我在命令行中写: javac Main.java
it creates the Main.class and automatically creates Test.class and for running this program I use: java Main它创建 Main.class 并自动创建 Test.class 和运行这个程序我使用: java Main

but when I add package myPack statement in the first line of two files everything changes.但是当我在两个文件的第一行中添加package myPack语句时,一切都发生了变化。 and the structure of the files is as follows:文件结构如下:

myPack我的包
├── Main.java ├── Main.java
└── Test.java └── 测试.java

If I write javac Main.java the compiler says:如果我写javac Main.java编译器会说:

Main.java:5: error: cannot find symbol Test t = new Test(); Main.java:5: 错误: 找不到符号 Test t = new Test();

and I should compile both of them at the same time.我应该同时编译它们。 (javac Main.java Test.java) (javac Main.java Test.java)

Question 1) Why it happens?问题1)为什么会发生?

Question 2) When I compiled both files I cant run program with java Main.问题 2)当我编译这两个文件时,我无法使用java Main 运行程序。

(Error: Could not find or load main class Main ). (错误:无法找到或加载主 class 主)。

What's the problem?有什么问题?

Question 3) I read somewhere you should compile and run this from the parent directory like this: javac myPack/Main.java (it automatically creates Test.class file) and then java myPack.Main .问题 3)我在某处读到您应该从父目录编译并运行它,如下所示: javac myPack/Main.java (它会自动创建 Test.class 文件),然后是 Z93F725A07423FE1C889F448B3D3 this way the program works properly.这样程序才能正常工作。 but why should we compile and run programs from the parent directory with this syntax?但是我们为什么要使用这种语法从父目录编译和运行程序呢?

Try this for compiling试试这个编译

# compile all files .java in folder ./myPack and outputing in ./folder-compiled
javac -d folder-compiled $(find ./myPack -name '*.java')

So you can run all compiled class with this所以你可以用这个运行所有编译的 class

# run all Main.class already compiled in ./folder-compiled
java -cp folder-compiled Main

this example above will work because I'm considering your classpath is in myPack/* and you are not working with modular classpath jdk9+ in other way may be diferent上面的这个例子会起作用,因为我正在考虑你的类路径在 myPack/* 中,而你没有使用模块化类路径 jdk9+ 以其他方式可能会有所不同

the other simple and easy way is working with building tools such as gradle or maven另一种简单易行的方法是使用构建工具,例如 gradle 或 maven

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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