【发布时间】:2017-01-26 11:34:57
【问题描述】:
前段时间我问怎么to make a class implement an interface that it doesn't implement by declaration。
一种可能性是as-coercion:
interface MyInterface {
def foo()
}
class MyClass {
def foo() { "foo" }
}
def bar() {
return new MyClass() as MyInterface
}
MyInterface mi = bar()
assert mi.foo() == "foo"
现在我尝试使用它,我不知道在编译时需要什么接口。我尝试使用这样的泛型:
interface MyInterface {
def foo()
}
class MyClass {
def foo() { "foo" }
}
class Bar {
public static <T> T bar(Class<T> type) {
return new MyClass() as T
}
}
MyInterface mi = Bar.bar(MyInterface.class)
assert mi.foo() == "foo"
但它引发了以下异常:
Cannot cast object 'MyClass@5c4a3e60' with class 'MyClass' to class 'MyInterface'
如何强制转换为仅在运行时才知道的接口?
【问题讨论】:
-
在将 Bar.bar(MyInterface.class) 转换为 MyInterface 时添加关键字“as”
-
我还需要能够从 Java 代码中调用
bar,所以它必须已经返回正确的类型。