Erik Hofer
Erik Hofer

Reputation: 2656

Groovy coercion to interface not known at compile-time

Some time ago I asked how to make a class implement an interface that it doesn't implement by declaration.

One possibility is 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"

Now that I try to use it, I don't know what interface is needed at compile-time. I tried using generics like this:

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"

But it raises the following exception:

Cannot cast object 'MyClass@5c4a3e60' with class 'MyClass' to class 'MyInterface'

How can I coerce to an interface that is only known at run-time?

Upvotes: 0

Views: 79

Answers (1)

Dany
Dany

Reputation: 1530

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"

Upvotes: 1

Related Questions