确定序列化对象的类型 [英] Determine type of serialized object
问题描述
我需要通过套接字发送消息(从用户到引擎的请求,以及从引擎到用户的响应).所以流量本质上是
I have a need to send messages (requests from the User to the Engine, and responses from the Engine to the User) over a socket. So the flow is essentially
+--------+ serialized request +--------+
| Server | <==== network ====> | Client |
+--------+ serialized response +--------+
^ ^
| request/response | mouse/keyclicks
| object |
v v
+--------+ +--------+
| Engine | | User |
+--------+ +--------+
现在,不在这里重新发明轮子才有意义.我正在处理双方的 Java,所以我计划像这样使用对象:
Now, it only makes sense to not reinvent the wheel here. I'm dealing with Java on both sides, so I plan use Objects like so:
/**
* A Client makes a Request.
*/
abstract class UserRequest implements Serializable {
/**
* The engine will call request.engineCallback(this);
* This will tell the Engine what the request is, at which point
* the Engine will determine its response.
*/
abstract EngineResponse engineCallback(Engine engine);
}
/**
* The Engine has calculated a Response.
*/
abstract class EngineResponse implements Serializable {
/**
* The User will call response.userCallback(this);
* This tells the User what the Engine thought of its request,
* and what happened as a result.
*/
abstract void userCallback(User user);
}
我没有关注的是,在我的服务器和客户端套接字中,我如何知道请求和响应的子类正在传入?我看到了这样的情况
What I'm not following is, in my Server and Client sockets, how will I know what subclass of Request and Response is coming in? I see a situation like
Object request = in.readObject();
// now what? How do I know what to cast it to?
// Can I just cast it like
UserRequest request = (UserRequest)(in.readObject());
engine.addToRequestQueue(request); // let it take care of implementation details?
我的第一个想法是通过字符串传递所有内容,但是当 Java 提供序列化时,这似乎有点愚蠢.但是我如何确保我知道哪个类遇到了电线?就此而言,我是否需要知道,只要我只将 UserRequest 的死者发送到服务器并将 EngineResponse 发送到客户端?
My first thought was to just pass everything through over Strings, but that seemed a bit silly when Java provides Serialization. But how do I make sure I know what class came across the wire? For that matter, do I need to know, as long as I only send decedents of UserRequest to the server and EngineResponse to the client?
推荐答案
只需使用提供的 instanceof
关键字:
Just use the instanceof
keyword provided:
Object o = in.readObject();
if (o instanceof SomeUserRequest)
{
SomeUserRequest sur = (SomeUserRequest)o;
..
}
else if (o instanceof OtherUserRequest)
{
..
}
这篇关于确定序列化对象的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!