Gradle中如何查看指定任务的属性?
你提到的gradle tasks能列出项目所有任务,但要查看单个任务(比如compileJava)的属性,有几种实用的方法:
方法1:使用Gradle内置的help --task命令
这个命令会展示目标任务的核心信息,包括它的类型、所属分组、描述,以及关键的输入输出属性(比如compileJava的source、destinationDir等)。执行命令:
gradle help --task compileJava
输出示例大概是这样:
Task :compileJava
Path
:compileJavaType
JavaCompile (org.gradle.api.tasks.compile.JavaCompile)Description
Compiles main Java source files.Group
buildInputs
- source (set of File)
- classpath (file collection)
...
Outputs
- destinationDir (directory)
...
这个方法的好处是不用修改任何构建脚本,直接通过内置命令获取关键属性。
方法2:通过Groovy脚本打印任务所有属性
如果想看到任务的全部属性(包括继承来的通用属性,比如name、group、enabled等),可以用Gradle的命令行脚本功能,不用修改项目的build.gradle。执行以下命令:
gradle -q --no-build-cache -DtaskName=compileJava << 'EOF' task printTaskProps { doLast { def targetTask = project.tasks.findByName(project.getProperty('taskName')) if (targetTask) { println "=== All properties for task '${targetTask.name}' ===" targetTask.properties.sort().each { propKey, propValue -> // 过滤掉一些内部的Groovy属性,让输出更整洁 if (!propKey.startsWith('$') && !propKey in ['metaClass', 'class']) { println "- $propKey: ${propValue.toString().take(100)}..." } } } else { println "Error: Task '${project.getProperty('taskName')}' not found in the project!" } } } EOF
执行后会输出compileJava任务的所有可访问属性,包括自定义属性和Gradle内置的属性。你可以把taskName=compileJava换成任何你想查看的任务名。
方法3:在构建脚本中临时添加调试任务
如果你经常需要查看任务属性,可以在项目的build.gradle中添加一个通用的调试任务:
task printTaskProperties { dependsOn = [] // 不依赖任何其他任务 doLast { def taskName = project.hasProperty('targetTask') ? project.targetTask : 'compileJava' def task = tasks.findByName(taskName) if (task) { println "Properties for task '$taskName':" task.properties.each { k, v -> if (!k.startsWith('$') && k != 'metaClass') { println "$k: $v" } } } else { println "Task '$taskName' does not exist." } } }
之后执行:
gradle printTaskProperties -PtargetTask=compileJava
就能快速查看指定任务的属性了,用完可以随时删掉这个任务。
内容的提问来源于stack exchange,提问作者yurii.pitomets

