我有一些用Java编写的代码,其中使用了泛型。这是一个简单的版本:
// In Java
public interface Testable {
void test();
}
public class TestableImpl implements Testable {
@Override
public void test(){
System.out.println("hello");
}
}
public class Test {
public <T extends Testable> void runTest(Collection<T> ts){
System.out.println("Collection<T>");
for(T t: ts)
t.test();
}
public void runTest(Object o){
System.out.println("Object");
System.out.println(o);
}
}
// in Groovy - this is how I have to use the code
Test test = new Test()
test.runTest([new TestableImpl(), new TestableImpl()])
test.runTest([1,2,3]) //exception here
我很惊讶第二个方法调用被派发到了错误的方法(在我的Java理解中是错误的)。而不是调用Object
重载,却调用了Collection
。
我正在使用Groovy 2.1.9,Windows 7。
异常信息如下:
Caught: org.codehaus.groovy.runtime.typehandling.GroovyCastException:
Cannot cast object '1' with class 'java.lang.Integer' to class 'Testable'
org.codehaus.groovy.runtime.typehandling.GroovyCastException:
Cannot cast object '1' with class 'java.lang.Integer' to class 'Testable'
为什么?如何解决这个问题?
如何让Groovy调用与Java相同的方法?
编辑:为了进一步解释这个案例,我想写一个Spock测试(想象一下该方法返回某些东西,比如一个字符串..):
def "good dispatch"(in,out) {
expect:
test.runTest(in) == out
where:
in | out
new Object() | "a value for Object"
new Integer(123) | "a value for Object"
[1,2,3] | "a value for Object"
[new TestableImpl()] | "a value for Testable Collection"
}