就我而言,我想调试一个特定的文件,所以我在build.gradle 中包含了以下代码:
task execFile(type: JavaExec) {
main = mainClass
classpath = sourceSets.main.runtimeClasspath
if (System.getProperty('debug', 'false') == 'true') {
jvmArgs "-Xdebug", "-agentlib:jdwp=transport=dt_socket,address=8787,server=y,suspend=y"
}
systemProperties System.getProperties()
}
我可以运行:
gradle execFile -PmainClass=com.MyClass -Dmyprop=somevalue -Ddebug=true
自定义execFile 任务接收:
-
-PmainClass=com.MyClass:我要执行的main方法所在的类(在脚本中,main = mainClass)
-
-Dmyprop=somevalue:在调用System.getProperty("myprop") 的应用程序中检索其值的属性(在脚本中,需要systemProperties System.getProperties())
-
-Ddebug=true:在端口 8787 上启用调试的标志(在脚本中,请参见 if 条件,以及 address=8787,但端口可以更改,并且此标志名称也可以更改)。使用suspend=y 会暂停执行,直到将调试器附加到端口(如果您不希望这种行为,可以使用suspend=n)
对于您的用例,您可以尝试将jvmArgs ... 行后面的逻辑应用于您的特定任务(或使用tasks.withType(JavaExec) { ... } 应用于此类型的所有任务)。
使用此解决方案时,请勿使用 --debug-jvm 选项,因为您可能会收到关于属性 jdwp 被定义两次的错误消息。
更新(2020-08-10)
为了确保代码仅在我显式执行任务execFile 时运行(例如,在我刚刚构建 gradle 时不运行),我将代码更改为:
task execFile {
dependsOn 'build'
doLast {
tasks.create('execFileJavaExec', JavaExec) {
main = mainClass
classpath = sourceSets.main.runtimeClasspath
if (System.getProperty('debug', 'false') == 'true') {
jvmArgs "-Xdebug", "-agentlib:jdwp=transport=dt_socket,address=*:8787,server=y,suspend=y"
}
systemProperties System.getProperties()
}.exec()
}
}
查看更多信息:Run gradle task only when called specifically