当我有一个简单的类层次结构时,我正确地得到一个例外:
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'
但是如果我有一个Map的委托,那么没有强制转换异常。
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([:])
===> [:]
如果我委托给Integer,则异常返回:
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'
即使使用委派的地图,我还能做什么(如果有的话)来获得演员表异常?
感谢