Groovy-get和propertyMissing之间的区别? [英] Groovy - difference between get and propertyMissing?

查看:126
本文介绍了Groovy-get和propertyMissing之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我缺少一些东西.据我所知,如果没有属性,访问器或 getProperty 可用,则 get 是最后的选择.实际上,这是否意味着 get propertyMissing 做同样的事情?我知道 get 扩展了字段访问运算符,所以那里一定有事:-)

There is something that I am missing. From what I have seen, get is the last resort if there is no property, accessor or getProperty available. In effect, doesn't this mean the get and propertyMissing do the same thing? I know that get extends the field-access operator so there must be something going on there :-)

// Using get
class Foo {
    def name = 'Jahg'
    Object get(String name) {
        'called get'
    }
}

def f1 = new Foo()
assert f1.noexist == 'called get'
// get() is not called for the known property (name)
assert f1.name == 'Jahg'

// Using propertyMissing
class Bar {
    Object propertyMissing(String name) {
        'called propertyMissing'
    }
}

def f2 = new Bar()
assert f2.noexist == 'called propertyMissing'

// When both are defined, get() takes precedence
class Baz  {

    // This one is called
    Object get(String name) {
        'called get'
    }

    Object propertyMissing(String name) {
        'not called'
    }
}

def f3 = new Baz()
assert f3.noexist == 'called get'

推荐答案

嗯,不,它们是不一样的,如下所示:

Well, no, they're not the same, as is evidenced by the following:

class Baz  {
    String name = 'bob'

    Object propertyMissing(String name) {
        'not called'
    }
}

Baz b = new Baz()
assert b.getProperty('name') == 'bob'
assert b.getProperty('whatever') == 'not called'
assert b.name == 'bob'
assert b.whatever == 'not called'

普通的get(和getProperty)方法检查该属性是否存在,如果不存在,则调用propertyMissing.

The normal get (and getProperty) method checks to see if the property exists, then calls propertyMissing if it doesn't.

重载get时,会丢失propertyMissing功能.

When you overloaded get, you lost the propertyMissing functionality.

这篇关于Groovy-get和propertyMissing之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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