需求
我想用Gradle脚本执行下列Java类Hello123.java:
import java.util.Arrays;
public class Hello123 {
public static void main(String[] args) {
System.out.println("args:"+ Arrays.toString(args));
}
}
测试一:创建execute任务
build.gralde
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
task execute(type: {
main = System.getProperty("exec.mainClass")
classpath = sourceSets.main.runtimeClasspath
systemProperties System.getProperties()
if(System.getProperty("exec.args"))
args System.getProperty("exec.args").split()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
测试结果
测试二:重写run任务
build.gralde
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: "application"
mainClassName = "NonExistentClass"
task run (type: {
main = System.getProperty("exec.mainClass")
classpath = sourceSets.main.runtimeClasspath
systemProperties System.getProperties()
if(System.getProperty("exec.args"))
args System.getProperty("exec.args").split()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
测试结果
参考
Gradle to execute Java class (without modifying build.gradle)
What is the gradle equivalent of maven’s exec plugin for running Java apps?
gradle task pass arguments to java application
Problems passing system properties and parameters when running Java class via Gradle