如何懒惰地设置任务的属性? [英] How to set a property of a task lazily?

查看:65
本文介绍了如何懒惰地设置任务的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

task task1(type: ProduceFilesTaskType) {
   outDir = file("$projectDir/some/files")
}

task task2(type: ConsumeFilesTaskType) {
   fileList = file("$doSomething.outDir/somefolders/").listFiles().toList() // null pointer exception
}

我没有 ConsumeFilesTaskType 的来源,它需要 List< File>由 task1 生成的fileList .

I don't have the source of ConsumeFilesTaskType and it requires a List<File> fileList which is produced by task1.

现在,因为这些文件在配置阶段不存在,gradle在配置阶段失败,错误为由于没有文件,无法在空对象上调用方法toList().

Now because these files don't exist in configuration phase, gradle fails at configuration stage with error Cannot invoke method toList() on null object because there are no files.

我可能可以做到

task task2(type: ConsumeFilesTaskType) {
   fileList = new ArrayList<File>() // don't fail
   doFirst {
      fileList = file("$doSomething.outDir/somefolders/").listFiles().toList() // actual list of files
   }
}

这是标准方法还是有更好的方法来懒惰地设置/评估属性?

Is this the standard way or is there a better way to set/evaluate a property lazily?

推荐答案

在Gradle中有很多构造是惰性计算的.在某种程度上,Gradle建立在懒惰评估的思想之上.话虽如此,这也取决于ConsumeFilesTaskType的实现方式.如果任务本身没有懒惰地使用 fileList参数,那无济于事.

There are a lot constructs in Gradle that are lazily evaluated. In a way Gradle is built on top of the idea of lazy evaluation. That being said, it also depends on how your ConsumeFilesTaskType is implemented. Nothing can help if the task itself is not using the fileList parameter lazily.

如果fileList键入为 Iterable< File> ,或Gradle提供的类型为 FileCollection ,则可以在配置阶段将其分配给project.fileTree():

If the fileList is typed as Iterable<File>, or the Gradle provided type FileCollection, you can assign it to project.fileTree() at configuration phase:

Iterable<File> fileList;

task myTask {
    fileList = project.fileTree("build") // build might not exist at this moment
    
    doLast {
        fileList.forEach { println it.name }
    }
}

有一个类似的方法 project.files()创建一个ConfigurableFileCollection对象. project.files()文档在解释懒惰"意味着什么方面做得更好.和实况". project.fileTree()返回的ConfigurableFileTree也是懒惰的.区别在于ConfigurableFileTree会将添加的文件解释为根.进行迭代时,ConfigurableFileTree递归遍历这些根目录以为调用者收集实际文件.

There is a similar method project.files() that creates a ConfigurableFileCollection object. The project.files() documentation does a better job at explaining what it means by "lazy" and "live". project.fileTree() returns a ConfigurableFileTree that is also lazy and live. The difference is that ConfigurableFileTree interprets the files added as roots. When iterating, ConfigurableFileTree recursively traverses these root directories to collect actual files for the caller.

这篇关于如何懒惰地设置任务的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆