Groovy“无方法签名"对委托运行闭包 [英] Groovy 'No signature of method' running Closure against delegate

查看:99
本文介绍了Groovy“无方法签名"对委托运行闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个针对另一个Groovy对象作为委托执行的闭包.我可以做到:

I have a closure that's executed against another Groovy object as the delegate. I can do:

foo {
    bar {
        major = 1
    }
}

但是当我这样做时:

foo {
    bar {
        major 1
    }
}

我得到一个错误:

> No signature of method: my.Bar.major() is applicable for argument types (java.lang.Integer) values: [1]
Possible solutions: setMajor(java.lang.Integer), getMajor(), wait(), any(), setMajor(java.lang.String), wait(long)

栏看起来像:

class Bar {
    Integer major
    Integer getMajor() { return this.major }
    def setMajor(Integer val) { this.major = val }
}

我认为Groovy在处理属性引用时使getters/setters透明,并且引用bar.majorbar.get/setMajor()相同.我是否理解这是错误的,还是将Closure委托放入混合中时,元类查找路径是否有所不同?解决策略是DELEGATE_FIRST.

I thought Groovy made getters/setters transparent when dealing with property references and that referring to bar.major was the same as bar.get/setMajor(). Am I understanding this wrong, or does the meta class lookup route differ when you throw Closure delegates into the mix? The resolution strategy is DELEGATE_FIRST.

有关更多信息,请参见: http://forums.gradle.org/gradle/topics/groovy-no-signature-of-method-running-closure-against-delegate

For more context: http://forums.gradle.org/gradle/topics/groovy-no-signature-of-method-running-closure-against-delegate

推荐答案

,您还必须添加void major(Integer val). major = 1setMajor(1)的常规缩写,而major 1major(1)的缩写. (请参见可选括号 部分)

you would have to add also void major(Integer val). major = 1 is groovy-short for setMajor(1) while major 1 is short for major(1). (see Section Optional parenthesis)

可选括号

如果至少有一个参数并且没有歧义,那么Groovy中的方法调用可以省略括号.

Optional parenthesis

Method calls in Groovy can omit the parenthesis if there is at least one parameter and there is no ambiguity.

println "Hello world"
System.out.println "Nice cheese Gromit!"

例如:

class X {
    Integer major
    void major(Integer m) { major = m }
}

def x = new X()
x.major = 1 // x.setMajor(1)
assert x.major==1 // x.getMajor()==1
x.major 2 // x.major(2)
assert x.major==2

如果大量需要此行为,则可以在这种情况下添加methodMissing.例如:

If you need this behaviour alot, you can add a methodMissing for this case. E.g.:

class X {
    Integer major
    def methodMissing(String name, args) {
        if (this.hasProperty(name) && args.size()==1) {
            this."$name" = args[0]
        } else {
            throw new MissingMethodException(name, this.class, args)
        }
    }
}

def x = new X()
x.major = 1
assert x.major==1
x.major 2
assert x.major==2

这篇关于Groovy“无方法签名"对委托运行闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆