如何在build.gradle中定义和调用自定义方法 [英] How to define and call custom methods in build.gradle

查看:1625
本文介绍了如何在build.gradle中定义和调用自定义方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为我的项目的一部分,我需要从目录中读取文件,并在构建脚本中执行所有这些操作。对于每个文件,操作是相同的(读取一些sql查询并执行它)。我认为它是一个重复性的任务,最好是在一个方法中写。由于我是新来的gradle,我不知道应该如何。

解决方案

下面给出了一个方法:

  ext.myMethod = {param1,param2  - > 
//方法体在这里
}

请注意,这是为项目范围,即。全局可用于该项目,可以在构建脚本中的任何位置使用 myMethod(p1,p2)在等效于 project.myMethod (p1,p2)



该方法也可以在不同的作用域下定义,例如在任务中:

 任务myTask {
ext.myMethod = {param1,param2 - >
//方法体在这里
}

doLast {
myMethod(p1,p2)//这将解决在任务
中定义的'myMethod'
}


As part of my project, I need to read files from a directory and do some operations all these in build script. For each file, the operation is the same(reading some sql queries and execute it). I think its a repetitive task and better to write inside a method. Since I'm new to gradle, I dont know how it should be. Please help.

解决方案

One approach given below:

ext.myMethod = { param1, param2 ->
    // Method body here
}

Note that this gets created for the project scope, ie. globally available for the project, which can be invoked as follows anywhere in the build script using myMethod(p1, p2) which is equivalent to project.myMethod(p1, p2)

The method can be defined under different scopes as well, such as within tasks:

task myTask {
    ext.myMethod = { param1, param2 ->
        // Method body here
    }

    doLast {
        myMethod(p1, p2) // This will resolve 'myMethod' defined in task
    }
}

这篇关于如何在build.gradle中定义和调用自定义方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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