Groovy - get和propertyMissing之间的区别?

时间:2016-04-15 00:58:56

标签: groovy

我遗失了一些东西。根据我的看法,如果没有可用的属性,访问者或 getProperty get 是最后的选择。实际上,这并不意味着 get propertyMissing 做同样的事情吗?我知道 get 扩展了字段访问操作符,因此必须有一些东西: - )

// 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'

1 个答案:

答案 0 :(得分:2)

嗯,不,他们不一样,如下所示:

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,如果它没有。

当你重载get时,你失去了propertyMissing功能。