Java – groovy closures can extend abstract classes

I have an abstract Java class that needs to implement an onmessage method I know that closures can easily implement Java interfaces using the as keyword, but how to extend Abstract Java classes?

If it can't extend it, what's the best job in groovy in this case?

This is my usage in Java. I'm looking for something similar that can be done in groovy

MessageCallback callback = new MessageCallback() {
            @Override
            public void onMessage(Message message) {
                dosomething();
            }
        };

Message callback is my abstract class, and I want to use it in groovy in a similar way

Solution

I believe you should be able to:

def callback = [ onMessage:{ message -> doSomething() } ] as MessageCallback

Doesn't it work?

edit

To call the abstract class back from the map method, the only method I can find is:

// 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' )
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>