我有一个抽象 Java 类,需要实现一个方法 onMessage
。我知道闭包可以使用 as
关键字轻松实现 Java 接口(interface),但它如何扩展抽象 Java 类?
如果它不能扩展它,那么在 Groovy 中这种情况下最好的解决方法是什么?
这是我在 Java 中的用法,我正在寻找可以在 Groovy 中完成的类似的东西。
MessageCallback callback = new MessageCallback() {
@Override
public void onMessage(Message message) {
dosomething();
}
};
消息回调是我想在 Groovy 中以类似方式使用的抽象类。
最佳答案
我相信你应该能够做到:
def callback = [ onMessage:{ message -> doSomething() } ] as MessageCallback
这行不通吗?
编辑
要从 Map 方法调用返回抽象类,我能找到的唯一方法是:
// Dummy class for testing
abstract class MessageTest {
abstract void onMessage( msg ) ;
void done() { println "DONE!" }
}
// Create a Proxied instance of our class, with an empty onMessage method
def p = [ onMessage:{ msg -> } ] as MessageTest
// Then overwrite the method once we have access to the Proxy object p
p.metaClass.onMessage = { msg -> println msg ; p.done() }
// Test
p.onMessage( 'woo' )
关于java - Groovy 闭包可以扩展抽象类吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7092418/