【发布时间】:2014-01-28 00:08:59
【问题描述】:
我有一些使用泛型的 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
我很惊讶第二个方法调用被分派给了错误的方法(在我的 Javish 理解中是错误的)。而不是调用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"
}
【问题讨论】:
标签: java generics groovy casting spock