5

I just encountered a peculiar little problem:

javax.websocket.Session session = //...
// this works
newSession.addMessageHandler(new MessageHandler.Whole<String>() {

    @Override
    public void onMessage(String message) {
        MyWebSocket.this.onMessage(message);
    }
});
// these don't work
newSession.addMessageHandler((MessageHandler.Whole<String>) MyWebSocket.this::onMessage);
newSession.addMessageHandler((MessageHandler.Whole<String>) message -> MyWebSocket.this.onMessage(message));


void onMessage(String message) {
    System.out.println(message);
}

Does anybody know why lambda expressions won't work in this instance? There is no compile error, no exception, no nothing. The method ''onMessage'' is just not called.

I use Java 1.8.0_65 and the Tyrus reference implementation 1.9.

Romano Zumbé
  • 7,893
  • 4
  • 33
  • 55
Stefan S.
  • 3,950
  • 5
  • 25
  • 77

2 Answers2

3

please see https://blogs.oracle.com/PavelBucek/entry/websocket_api_1_1_released

tldr; you have to use Session#addMessageHandler(Class<T> clazz, MessageHandler.Whole<T> handler)

/**
* Register to handle to incoming messages in this conversation. A maximum of one message handler per
* native websocket message type (text, binary, pong) may be added to each Session. I.e. a maximum
* of one message handler to handle incoming text messages a maximum of one message handler for
* handling incoming binary messages, and a maximum of one for handling incoming pong
* messages. For further details of which message handlers handle which of the native websocket
* message types please see {@link MessageHandler.Whole} and {@link MessageHandler.Partial}.
* Adding more than one of any one type will result in a runtime exception.
*
* @param clazz   type of the message processed by message handler to be registered.
* @param handler whole message handler to be added.
* @throws IllegalStateException if there is already a MessageHandler registered for the same native
*                               websocket message type as this handler.
*/
public void addMessageHandler(Class<T> clazz, MessageHandler.Whole<T> handler);

in order to use lambdas as message handers.

Pavel Bucek
  • 5,304
  • 27
  • 44
-2

From my understanding MessageHandler would need to be a @FunctionalInterface to allow lambda expressions here, which isn't the case.

  • 1
    ["However, the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration."](https://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html) You don't need the Annotation to use it as lambda – F. Lumnitz Feb 29 '16 at 09:27
  • 1
    Also there would be a compile error if that was the case. – Stefan S. Feb 29 '16 at 09:34