4

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:

osfar's project directory structure

First I typed this in a cmd window to compile the module-info.java and Task.java files:

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?

This is the code for the class and the module descriptor:

module zoo.animal.feeding {
}
public class Task {
    public static void main(String... args) {
        System.out.println("All fed!");
    }
}
deduper
  • 1,944
  • 9
  • 22
osfar
  • 401
  • 1
  • 4
  • 23

1 Answers1

4

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)

Using the modulepath, a class is not allowed in the top-level directory of the project. So based on the directory structure, your Task.java file should include package description and look like -

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:

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. Then your execution using the following java command should work as expected.

java --module-path mods -m zoo.animal.feeding/zoo.animal.feeding.Task
Naman
  • 27,789
  • 26
  • 218
  • 353