Groovy – 繼承 Expando class 要小心

在程式裡有一個 POGO class, 今天突然想用動態的方式增加一個屬性, 就很自然地想到用 Expando, 於是就在這個 POGO class 加上入 extends Expando, 像這樣:

class MyClass extends Expando {
    String prop1 = 'Vito'
    String setProp1(String value) {
        this.prop1 = "[$value]"
    }
}

結果…用了 Expando 確實是達到了動態增加的目的, 但是原來定義在 POGO class 的 setter 卻找不到啦…應該是說, 不會被呼叫到了:

assert my.prop1 == "Vito"
my.prop1 = "ABC"
assert my.prop1 == "ABC"

如上例, 設定 prop1 = ‘ABC’, 因為有 setter, 因此正確值應為 ‘[ABC]’, 但最後結果卻是 ‘ABC’
我想這應該算是一個 groovy bug 吧…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s