groovyexpandometaclass

Expando Metaclass behaviour dependant on whether a class is user defined or not?


While experimenting with ExpandMetaClass I ran into this behaviour:

class A {}

A.metaClass.foo = { 0 }
A.metaClass.foo = { 1 }
println (new A().foo())
A.metaClass.foo = { 2 }
println (new A().foo())

Collection.metaClass.foo = { 0 }
Collection.metaClass.foo = { 1 }
println ([].foo())
Collection.metaClass.foo = { 2 }
println ([].foo())

Which prints

1
2
1
1

Which doesn't seem to be consistent. What's the rationale behind this behavior?


Solution

  • Sounds like a bug. You should fill a JIRA.

    It works per instance:

    class A {}
    
    A.metaClass.foo = { 0 }
    A.metaClass.foo = { 1 }
    assert (new A().foo()) == 1
    A.metaClass.foo = { 2 }
    assert (new A().foo()) == 2
    
    Collection.metaClass.foo = { 0 }
    Collection.metaClass.foo = { 1 }
    assert ([].foo()) == 1
    
    def j = []
    j.getMetaClass().foo = { 2 }
    assert (j.foo()) == 2