gpt4 book ai didi

java - gradle/groovy:从自定义类调用 'global'函数

转载 作者:行者123 更新时间:2023-12-03 03:12:06 28 4
gpt4 key购买 nike

我不熟悉groovy / gradle
据我了解,gradle / groovy与Java兼容。

我在“build.gradle”文件中编写了以下gradle(没有任何任务):

def myFun = {->"Hello World"}

class MyClass {
String getLabel() {
return ""+ myFun();
}
}

System.err.println(new MyClass().getLabel());

其中 MyClass类调用'global'(?)函数 myFun

调用 gradle --tasks会产生以下错误:
FAILURE: Build failed with an exception.

* Where:
Build file 'build.gradle' line: 6

* What went wrong:
A problem occurred evaluating root project 'tmp'.
> No signature of method: MyClass.myFun() is applicable for argument types: () values: []
Possible solutions: find(), find(groovy.lang.Closure), wait(), any(), every(), dump()

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 2.671 secs

如何使此类 MyClass可以“查看”函数 myFun

谢谢。

最佳答案

您不能直接,因为Groovy中没有全局变量。您可以修改声明以传递当前类的实例,以便可以调用myFun闭包:

@groovy.transform.Field 
def myFun = {-> "Hello World"}

class MyClass {
String getLabel(script) {
return ""+ script.myFun();
}
}

System.err.println(new MyClass().getLabel(this))

或者,您可以使用 binding对象,但这是相同的模式。

有关更多信息:
  • Groovy scope - how to access script variable in a method
  • https://stackoverflow.com/a/35418596/862594
  • 关于java - gradle/groovy:从自定义类调用 'global'函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53541694/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com