2017-01-26 5 views
0

いくつかの時間前に私はどのようにしてto make a class implement an interface that it doesn't implement by declarationを尋ねました。コンパイル時に知られていないインターフェースへのGroovyの強制

一つの可能​​性は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 '[email protected]' with class 'MyClass' to class 'MyInterface' 

私は実行時にのみ知られているインターフェイスに強制できますか?

+0

私はそれが既に正しい型を返す必要がありますので、同様にJavaコードから 'bar'を呼び出すことができるようにする必要がありMyInterface –

+0

としてBar.bar(MyInterface.class)をキャストしながら、「と」キーワードを追加します。 –

答えて

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"