Groovy强制接口在编译时不知道

时间:2017-01-26 11:34:57

标签: groovy coercion

前段时间我问过to make a class implement an interface that it doesn't implement by declaration

一种可能性是as - 胁迫:

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'

如何强制使用仅在运行时知道的接口?

1 个答案:

答案 0 :(得分:1)

interface MyInterface {
    def foo()
}

interface AnotherInterface {
    def foo()
}

class MyClass {
    def foo() { "foo" }
}

class Bar {
    static <T> T bar(Class<T> type) {
        new MyClass().asType(type)
    }
}


MyInterface mi = Bar.bar(MyInterface)
assert mi.foo() == "foo"

AnotherInterface ai = Bar.bar(AnotherInterface)
assert ai.foo() == "foo"