【问题标题】:Groovy coercion to interface not known at compile-timeGroovy 强制转换到编译时未知的接口
【发布时间】: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,所以它必须已经返回正确的类型。

标签: groovy coercion


【解决方案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"

【讨论】:

    猜你喜欢
    • 2015-02-23
    • 2012-08-25
    • 2011-05-28
    • 1970-01-01
    • 2013-04-17
    • 1970-01-01
    • 2013-11-18
    • 2015-04-11
    相关资源
    最近更新 更多