[英]Error while trying to compile and run sample module in Java
I'm new to the topic of modules, and I'm following a simple example of how to create, compile and run them.我是模块主题的新手,我正在关注如何创建、编译和运行它们的简单示例。
The folder structure of my project is illustrated in the following diagram:我项目的文件夹结构如下图所示:
First I typed this in a cmd window to compile the module-info.java and Task.java files:首先,我在 cmd window 中输入这个来编译 module-info.java 和 Task.java 文件:
javac --module-path mods -d feeding feeding/zoo/animal/feeding/Task.java feeding/module-info.java
Then I tried to run the code with the following:然后我尝试使用以下代码运行代码:
java --module-path feeding --module zoo.animal.feeding/zoo.animal.feeding.Task
I get the following error:我收到以下错误:
Error occurred during initialization of boot layer
java.lang.module.FindException: Error reading module: feeding
Caused by: java.lang.module.InvalidModuleDescriptorException: Task.class found in top-level directory (unnamed package not allowed in module)
Can someone resolve this?有人可以解决这个问题吗? Also, what is the role of the
--module-path
option in both the java
and javac
commands?另外,
--module-path
选项在java
和javac
命令中的作用是什么?
This is the code for the class and the module descriptor:这是 class 和模块描述符的代码:
module zoo.animal.feeding {
}
public class Task {
public static void main(String... args) {
System.out.println("All fed!");
}
}
It's pretty straight forward to solve as per what the error message reads.根据错误消息的内容来解决是非常直接的。
Caused by: java.lang.module.InvalidModuleDescriptorException: Task.class found in top-level directory (unnamed package not allowed in module)
Caused by: java.lang.module.InvalidModuleDescriptorException: Task.class 在顶级目录中找到(未命名的 package 不允许在模块中)
Using the modulepath, a class is not allowed in the top-level directory of the project.使用模块路径,项目的顶级目录中不允许出现 class。 So based on the directory structure, your
Task.java
file should include package description and look like -所以根据目录结构,你的
Task.java
文件应该包含 package 描述并且看起来像 -
package zoo.animal.feeding;
public class Task {
public static void main(String... args) {
System.out.println("All fed!");
}
}
The compilation(from the command line directory where mods
and feeding
reside) would continue such as:编译(从
mods
和feeding
所在的命令行目录)将继续,例如:
javac -d mods feeding/module-info.java feeding/zoo/animal/feeding/Task.java
should help you relevant .class
files in the corresponding directories under mods
as output folder.应该帮助你相关的
.class
文件在mods
下的相应目录中作为output文件夹。 Then your execution using the following java command should work as expected.然后您使用以下 java 命令执行应该按预期工作。
java --module-path mods -m zoo.animal.feeding/zoo.animal.feeding.Task
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.