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

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

问题描述

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

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.

推荐答案

下面给出一种方法:

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

请注意,这是为项目范围创建的,即.项目全局可用,可以在构建脚本中的任何地方使用 myMethod(p1, p2) 调用,它相当于 project.myMethod(p1, p2)

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天全站免登陆