2016-02-29 85 views
5

我只是遇到了一個奇特的小問題:LAMBDA不起作用在WebSocket的會議

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); 
} 

有誰知道爲什麼lambda表達式不會在這種情況下工作嗎?有沒有編譯錯誤,也不例外,什麼都沒有。該方法'的onMessage'只是不叫。

我使用Java 1.8.0_65和泰魯斯參考實現1.9。

回答

2

請參閱https://blogs.oracle.com/PavelBucek/entry/websocket_api_1_1_released

tldr;你必須使用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); 

爲了使用lambda表達式作爲消息左撇子。

-2

從我的理解MessageHandler將需要是@FunctionalInterface允許lambda表達式在這裏,情況並非如此。

+1

[「然而,編譯器將治療會議功能接口的定義作爲一個功能接口不管一個FunctionalInterface註釋是否存在於接口聲明任何接口。」](https://docs.oracle。 COM/JavaSE的/ 8 /文檔/ API/JAVA/LANG/FunctionalInterface.html) 你不需要註釋使用它作爲拉姆達 –

+1

而且會有一個編譯錯誤,如果是這樣的話。 –