使用 gradle “run” 任务运行主方法

2022-09-01 09:41:18

我想通过 gradle 任务运行我的方法main

这就是我通过cmd运行的方式:

java -cp RTMonitor.jar com.bla.MainRunner first_arg

它应该如何写成 gradle?

run {
    args += ['java -cp RTMonitor.jar com.bla.MainRunner first_arg']
}

更新

我试过

task myRun(type: JavaExec) {
    classpath configurations.main
    main = "com.bla.runners.StatsLogGenerator"
    args "arg1", "arg2"
}

我得到了:

Error:(71, 0) Could not find property 'main' on configuration container.

the I have tried:
    task myRun(type: JavaExec) {
        classpath "configurations.main"
        main = "com.bla.runners.StatsLogGenerator"
        args "arg1", "arg2"
    }

我得到了一个错误:

FAILURE: Build failed with an exception.
17:49:21.855 [ERROR] [org.gradle.BuildExceptionReporter] 
17:49:21.856 [ERROR] [org.gradle.BuildExceptionReporter] * What went wrong:
17:49:21.856 [ERROR] [org.gradle.BuildExceptionReporter] Execution failed for task ':myRun'.
17:49:21.856 [ERROR] [org.gradle.BuildExceptionReporter] > Process 'command '/Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/bin/java'' finished with non-zero exit value 1
17:49:21.864 [ERROR] [org.gradle.BuildExceptionReporter] 
17:49:21.865 [ERROR] [org.gradle.BuildExceptionReporter] * Exception is:
17:49:21.866 [ERROR] [org.gradle.BuildExceptionReporter] org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':myRun'.
17:49:21.867 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69)

17:49:21.882 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.process.internal.DefaultExecHandle$ExecResultImpl.assertNormalExitValue(DefaultExecHandle.java:361)
17:49:21.882 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.process.internal.DefaultJavaExecAction.execute(DefaultJavaExecAction.java:31)

但是当我通过Intellij运行时,每个thig都工作正常


答案 1

最简单的可能是使用应用程序插件。添加到您的 build.gradle 并设置 。向主类添加参数,请修改运行任务并编辑 args 属性apply plugin: 'application'mainClassName = com.bla.MainRunner

run {
  args += 'first_arg'
}

类路径是从主 sourceSet 自动获取的,如果需要不同的类路径,可以编辑运行任务的类路径属性。

如果你需要更多的自定义,你可以定义你自己的JavaExec类型的任务,就像这样

task myRun(type: JavaExec) {
  classpath sourceSets.main.runtimeClasspath
  main = "com.bla.MainRunner"
  args "arg1", "arg2"
}

答案 2
task run(type: JavaExec) {
  group = 'Run' // <-- change the name as per your need
  description = 'Small description what this run will do'

  classpath sourceSets.main.runtimeClasspath // <-- Don't change this
  main = "com.mypackage.myclassNameContaingMainMethod"
  args "arg1", "arg2"
}

这是一个独立的已注册任务,还可以具有任务的组和描述以及其他属性。


推荐