Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
class A{
  String text
}
def a1= new A(text: 'aBCdefG')
assert a1.metaClass.adaptee.class == MetaClassImpl //usual MetaClass type

A.metaClass.inSameCase= {-> text.toUpperCase()}
    //triggers conversion of MetaClass of A to ExpandoMetaClass
    //then adds new instance method 'inUpperCase' to class

def a2= new A(text: 'hiJKLmnOp')
assert a2.metaClass.adaptee.getClass() == ExpandoMetaClass
  //MetaClass of A changed for instances created after conversion trigger only
assert a2.inSameCase() == 'HIJKLMNOP'

assert a1.metaClass.adaptee.class == MetaClassImpl //still usual MetaClass type
try{ println a1.inSameCase(); assert false }
catch(e){ assert e in MissingMethodException } //new method not available

A.metaClass.inLowerCase= {-> text.toLowerCase()}
assert a2.inLowerCase() == 'hijklmnop'

//we can replace the method definition with another
A.metaClass.inSameCase= {-> text.toLowerCase()}
assert a2.inSameCase() == 'hijklmnop'

A.metaClass.inSameCase= null //remove method
try{ println a1.inSameCase(); assert false }
catch(e){ assert e in MissingMethodException } //method no longer available

//we can add static methods...
A.metaClass.'static'.inSameCase= { it.toLowerCase()}
assert A.inSameCase('qRStuVwXyz') == 'qrstuvwxyz'

...