gpt4 book ai didi

java - Groovy:访问静态类闭包内的全局变量

转载 作者:行者123 更新时间:2023-12-01 19:36:03 25 4
gpt4 key购买 nike

我正在运行下面的代码片段,但不确定如何解决访问返回闭包的类的静态方法内的tr变量。

tr = 'GROOVY'

class tmp {
static map = {
def cols = [ header: { "JAVA" }, trailer: { tr } ]
}
}

tmp.map().collect { k,v -> println v()}

运行时抛出以下错误。

JAVA
Caught: groovy.lang.MissingPropertyException: No such property: tr for class: tmp
Possible solutions: map
groovy.lang.MissingPropertyException: No such property: tr for class: tmp
Possible solutions: map
at tmp$__clinit__closure1$_closure3.doCall(test.groovy:31)
at tmp$__clinit__closure1$_closure3.doCall(test.groovy)
at test$_run_closure1.doCall(test.groovy:35)
at test.run(test.groovy:35)
[Finished in 2.0s with exit code 1]

最佳答案

您可以使用Groovy Binding class目的。它用于将值传入和传出 Groovy 脚本。默认情况下,有一个可用于脚本的易于使用的绑定(bind)对象。在类外部声明的属性会自动添加到该对象中。

tr = 'GROOVY'

class Tmp {
static Binding context
static map = {
def cols = [header: { "JAVA" }, trailer: { context.tr }]
}
}

Tmp.context = binding
Tmp.map().collect { k, v -> println v() }

最好创建自己的绑定(bind)对象(或者我应该说上下文),而不是依赖默认对象,如下所示:

def myBinding = new Binding(['tr': 'Groovy'])

class Tmp {
static Binding context
static map = {
def cols = [header: { "JAVA" }, trailer: { context.tr }]
}
}

Tmp.context = myBinding
Tmp.map().collect { k, v -> println v() }

关于java - Groovy:访问静态类闭包内的全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57501709/

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