问题描述
我缺少一些东西.据我所知,如果没有属性,访问器或 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之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!