我有一个通过套接字连接的客户端-服务器应用程序。我的 MessageHandler 类负责处理传入和传出消息。我传递了填充请求和回调所需的参数,我希望在收到响应后调用它们。我将回调存储在具有唯一请求标识符的哈希映射中。当收到响应时,我从哈希映射中获取回调,调用它并将响应作为参数传递。这是代码
class MessageHanlder {
val callbacks = new HashMap[String, (AnyRef) => Unit]
def sendAuthRequest(login: String, password: String, callback: Option[(AnyRef) => Unit]) {
val requestId = generateRequestId()
// create a packet with requestId, login and password
// send the packet
if(callback.isDefined) callbacks += ((requestId, callback.get))
}
private def generateRequestId() = // returns random string
def handleAuthResponse(authResponse: AuthResponse) {
val requestId = authResponse.requestId
val callbackOption = callbacks.get(requestId)
if(callbackOption.isDefined) callbackOption.get(authResponse)
}
def sendServerInfoRequest(callback: Option[(AnyRef) => Unit]) {
val requestId = generateRequestId()
// create a packet with requestId
// send the packet
if(callback.isDefined) callbacks += ((requestId, callback.get))
}
def handleServerInfoResponse(serverInfoResponse: ServerInfoResponse) {
val requestId = serverInfoResponse.requestId
val callbackOption = callbacks.get(requestId)
if(callbackOption.isDefined) callbackOption.get(serverInfoResponse)
}
我的问题是回调的参数类型。它可以是 ServerInfoResponse 或 AuthResponse 或任何其他响应类型。每个响应都有自己的一组字段,我想从回调中访问这些字段。要将回调保存到 hashmap 中,我必须将参数类型概括为 AnyRef。所以在回调中我必须将 AnyRef 转换为这样的具体类型
val serverInfoCallback = (response: AnyRef) => {
val serverInfoResponse = response.asInstanceOf[ServerInfoResponse] // explicit cast
val name = serverInfoResponse.name
val numberOfCores = serverInfoResponse.numberOfCores
// so on
}
有什么办法可以避免铸造?还是有更正确的方法来实现回调系统?
谢谢!