方法闭包的属性缺失
当我在 groovysh 中尝试此代码时:
def foo(s) {
s.trim()
}
a = foo
一切都按预期工作,但是当我在 IDE (Intellij idea) 中尝试它时,我得到:
Caught: groovy.lang.MissingPropertyException: No such property: foo for class: Test
at Test.run(Test.groovy:5)
编辑: 与 Eclipse 相同。
groovysh 将方法转换为闭包有什么秘密吗?
不幸的是,我无法使用通常的 this.&foo
语法,因为代码是 DSL 的一部分,我想让它不那么冗长。
格罗维 1.8
When I try this code in groovysh:
def foo(s) {
s.trim()
}
a = foo
everything works as expected, but when I try it in IDE (Intellij idea) I get:
Caught: groovy.lang.MissingPropertyException: No such property: foo for class: Test
at Test.run(Test.groovy:5)
EDIT: Same with Eclipse.
Is there any secret how groovysh converts methods to closures?
Unfortunately, I can't use the usual this.&foo
syntax as the code is a part of DSL and i would like to make it less verbose.
Groovy 1.8
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它在 groovy 控制台中对我不起作用,而且我也不希望它起作用,因为 foo 是一个函数,而您试图在变量 a 中存储对它的引用。您只能在变量中存储对闭包的引用,因此您应该将
foo
重新定义为闭包,或者将其定义为函数并使用
.&
运算符将其转换为一个闭包It doesn't work for me in the groovy console and I wouldn't expect it to, because
foo
is a function and you're trying to store a reference to it in the variablea
. You can only store references to closures in variables, so you should either redefinefoo
as a closureor define it as a function and use the
.&
operator to convert it to a closure在groovysh的Interpreter.groovy中有一行:
context["${m.name}"] = new MethodClosure(type.newInstance(), m.name)
我认为它回答了我的问题。
In groovysh's Interpreter.groovy there is a line:
context["${m.name}"] = new MethodClosure(type.newInstance(), m.name)
I think it answers my question.