執行沒有參數的 main class
Java 
package examples;
public class TestMain {
    public static void main(String[] params) {
        System.out.println("hello");
    }
}
build.gradle
apply plugin: 'java'
apply plugin: 'application'
mainClassName= 'examples.TestMain'

repositories {
    mavenCentral()
}

dependencies {
    testCompile 'junit:junit:4.12'
}
執行
$ gradle run

> Task :run
hello

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.3/userguide/command_line_interface.html#sec:command_line_warnings


BUILD SUCCESSFUL in 952ms
3 actionable tasks: 3 executed

執行帶有寫死參數的 main class
Java
package examples;
public class TestMain {
    public static void main(String[] params) {
        System.out.println("hello " + params[0]);
    }
}
build.gradle
apply plugin: 'java'
apply plugin: 'application'
mainClassName= 'examples.TestMain'

repositories {
    mavenCentral()
}

dependencies {
    testCompile 'junit:junit:4.12'
}

run.args = ['abc']
執行
apply plugin: 'java'
apply plugin: 'application'
mainClassName= 'examples.TestMain'

repositories {
    mavenCentral()
}

dependencies {
    testCompile 'junit:junit:4.12'
}

run.args = ['abc']

執行帶有命令列參數的 main class
Java
package examples;
public class TestMain {
    public static void main(String[] params) {
        System.out.println("hello " + params[0]);
    }
}
build.gradle
apply plugin: 'java'
apply plugin: 'application'
mainClassName= 'examples.TestMain'


repositories {
    mavenCentral()
}


dependencies {
    testCompile 'junit:junit:4.12'
}
run.args = [project.args] //simply args can work as well
執行
$ gradle clean run -Pargs=ABC

> Task :run
hello ABC

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.3/userguide/command_line_interface.html#sec:command_line_warnings

BUILD SUCCESSFUL in 760ms
4 actionable tasks: 4 executed







Tags:

Updated: