如果B
实现A
(Java类),ABUtils
有方法:
public A getBar(String s)
{
return new B(s);
}
以下代码有什么问题:
import A
import B
def foo = ABUtils.getBar("blah");
为什么会产生:
org.codehaus.groovy.runtime.typehandling.GroovyCastException:
Cannot cast object 'blah' with class 'B' to class 'A'
答案 0 :(得分:1)
完全没问题。
A.java:
public interface A {}
B.java:
public class B implements A {}
ABUtil.groovy:
class ABUtils {
A getBar() { new B() }
}
new ABUtils().bar.with {
assert it instanceof A
assert it instanceof B
}
编译并运行:
$ javac *.java && groovy AB.groovy
$