2

How to run a Java class with a main method from Idea in project managed by Gradle in a modular way?

For class like

package org.example.moduledemo;

public class Main {
    public static void main(String[] args) {
        System.out.printf("Main module %s%n", System.getProperty("jdk.module.main"));
        System.out.printf("Main module class %s%n", System.getProperty("jdk.module.main.class"));
        System.out.printf("Module name %s%n", Main.class.getModule().getName());
    }
}

when run in modular way using java --module-path '.\build\classes\java\main' --module org.example.moduledemo/org.example.moduledemo.Main, it prints

Main module org.example.moduledemo
Main module class org.example.moduledemo.Main
Module name org.example.moduledemo

However when a "Run 'Main.main()'" is selected from Idea editor context menu

Run editor context menu,

it creates a Run configuration with class-path

Run configuration with class-path.

Even when the "Use classpath of module" option is unchecked, and the configuration looks like

Run configuration not using module classpath,

it still invokes the app using command-line

"C:\Program Files\Java\jdk-23\bin\java.exe" -Dfile.encoding=UTF-8 -Duser.country=US -Duser.language=en -Duser.variant -cp C:\moduledemo-gradle\build\classes\java\main;C:\moduledemo-gradle\build\resources\main org.example.moduledemo.Main

and the application output shows that it's not run in modular way:

Main module null
Main module class null
Module name null

Project layout Project layout

Invoking context menu "Run ...main()" action starts the application in modular way when the project is built by Idea itself (i.e. not managed by Gradle).

I'd like to keep using the Idea "Run ...main()" action for it's simplicity. I'm aware of workarounds like Gradle application plugin or Gradle exec task.

3
  • I think you need to specify that you want to use modules in your build gradle. Commented Dec 8, 2024 at 22:58
  • If you refer to the snippet application { mainModule = ... } on the linked page, it doesn't seem to have any effect on behavior of Idea's Run action. Commented Dec 8, 2024 at 23:31
  • If you have the application plugin applied with the appropriate configurations, then create a Gradle run configuration in IntelliJ and have it execute the run task. Assuming java.modularity.inferModulePath is true (the default in modern versions of Gradle) and application.mainModule is set, then the run task should handle setting the --module-path and --module options for you. Commented Dec 9, 2024 at 5:44

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.