Search code examples
javaexceptiongradlecommand-linemain-method

How do I run a main method in a Java Gradle project from command line?


I have a Gradle project (say, MyProject) that has a main method that I only want to use to run a small Java app. Say, the script is in a class and package as follows:

MyScript.Java

package com.car.ant;

import com.3rdparty.library.LibraryException;

public class MyScript {
    public static void main(String[] args) {
        System.out.println("Hello world!");
    }
}

I build the project with $ ./gradlew clean build, no problem. I am trying to run this via command line, but when I do, I get an Exception when trying to run:

$ pwd
~/workspace/MyProject/build/classes/java/main
$ java com.car.ant.MyScript
Exception in thread "main" java.lang.NoClassDefFoundError: com/3rdparty/library/exception/LibraryException
        at java.lang.Class.getDeclaredMethods0(Native Method)
        at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
        at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
        ... 7 more

This script is not the main part of the app, but I just want it in there to run every once in a while, and I'd like to figure out how to run it by itself command line. Is there a way to do this without importing anymore libraries? I've seen this done with one-jar, but I thought I could do this without one-jar.

UPDATE:

Tried to add a classpath after reading this, but now I'm getting a different error:

$ java -cp com/3rdparty/library/exception/LibraryException com.car.ant.MyScript
Error: Could not find or load main class com.car.ant.MyScript

Solution

  • You can read about how to do this at the Gradle Docs.

    apply plugin: 'application'
    mainClassName = "com.mycompany.myapplication.MyScript"
    applicationDefaultJvmArgs = [
        "-Djava.util.logging.config.file=src/main/resources/logging.properties"
    ]
    

    Then simply use gradlew run to run your application.

    As an added benefit, this plugin helps you to package your app for distribution. Use the gradle distZip command for that.