简体   繁体   English

如何从gradle中的不同文件引用方法

[英]How to refer a method from a different file in gradle

The only thing I know we can do is have build.gradle and have the following defined at the top for example to reference from other.gradle files我知道我们唯一能做的就是拥有 build.gradle 并在顶部定义以下内容,例如从 other.gradle 文件中引用

apply from: 'common-methods.gradle'

But I want to do the same thing inside a different gradle file.但我想在不同的 gradle 文件中做同样的事情。

Example:例子:

output.gradle输出.gradle

apply from: 'gradle/common.gradle'

task output{
    doLast{
        outputResults()
    }
}

def outputResults()
{
   def output = ResultGrabber()
   logger.quiet("I have the output saved")
}

common-method.gradle通用方法.gradle

def ResultGrabber()
{
   return 1
}

When I did something similar I got an error that it doesn't know the method.当我做类似的事情时,我得到一个错误,它不知道该方法。 I am not an expert at gradle but I have a feeling build.gradle is special compared to other.gradle type files.我不是 gradle 专家,但我觉得 build.gradle 与 other.gradle 类型的文件相比很特别。 If thats the case then is there an alternative solution?如果是这样,那么是否有替代解决方案?

For some weird reason I got it working when I placed the definition of my method inside build.gradle.出于某种奇怪的原因,当我将我的方法定义放在 build.gradle 中时,我让它工作了。 So this is what my file structure looks like which works now所以这就是我的文件结构现在可以使用的样子

build.gradle构建.gradle

apply from: 'gradle/output-method.gradle'

def outputResults()
{
   logger.quiet("I have the output saved")
   return 1
}

output-method.gradle输出方法.gradle

doLast{
logger.quiet("Starting method")
outputResults()
logger.quiet("Ending method")
}

To be honest I am a bit shocked this worked because its build.gradle that's referencing output-method.gradle and not the otherway around.老实说,我有点震惊,因为它的 build.gradle 引用了 output-method.gradle 而不是其他方式。 I made sure there was no pathing issue but in any case this solution allows me to avoid using duplicate code.我确保没有路径问题,但无论如何这个解决方案让我避免使用重复代码。 I had mentioned in my post earlier that I already knew we could do something similar with build.gradle but I can't find any other working way.我在之前的帖子中提到过,我已经知道我们可以用 build.gradle 做类似的事情,但我找不到任何其他工作方式。 Someone had posted about defining my method inside./buildSrc/src/groovy/ - but I haven't tested that out yet有人发布了关于在内部定义我的方法。/buildSrc/src/groovy/ - 但我还没有测试过

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM