Groovy类型强制转换和委托

Groovy类型强制转换和委托,groovy,Groovy,当我有一个简单的类层次结构时,我正确地得到了一个异常: groovy:000> class Parent {} ===> true groovy:000> class Child1 extends Parent {} ===> true groovy:000> class Child2 extends Parent {} ===> true groovy:000> Child1 c = new Child2() ERROR org.codehaus.gr

当我有一个简单的类层次结构时,我正确地得到了一个异常:

groovy:000> class Parent {}
===> true
groovy:000> class Child1 extends Parent {}
===> true
groovy:000> class Child2 extends Parent {}
===> true
groovy:000> Child1 c = new Child2()
ERROR org.codehaus.groovy.runtime.typehandling.GroovyCastException:
Cannot cast object 'Child2@74bada02' with class 'Child2' to class 'Child1'
但如果我有一个映射的委托,那么就没有强制转换例外

groovy:000> class Parent {@Delegate private Map wrappedMap; 
                          Parent(Map m) { wrappedMap = m } }
===> true
groovy:000> class Child1 extends Parent { Child1(Map m) { super(m) } }
===> true
groovy:000> class Child2 extends Parent { Child2(Map m) { super(m) } }
===> true
groovy:000> Child1 c = new Child2([:])
===> [:]
如果委托给整数,则异常返回:

groovy:000> class Parent {@Delegate private Integer i; 
                          Parent(Integer iparam) { i = iparam } }
===> true
groovy:000> class Child1 extends Parent { Child1(Integer iparam) { super(iparam) } }
===> true
groovy:000> class Child2 extends Parent { Child2(Integer iparam) { super(iparam) } }
===> true
groovy:000> Child1 c = new Child2(3)
ERROR org.codehaus.groovy.runtime.typehandling.GroovyCastException:
Cannot cast object 'Child2@232a7d73' with class 'Child2' to class 'Child1'
即使有委托映射,我还能做什么(如果有的话)来获得cast异常

谢谢