我在练习用java进行socket通信,尤其是交换服务器端和客户端知道的对象。如果我只发送一种类类型(消息),我可以轻松地转换和重建它:
while (!socket.isClosed()) {
try {
Message message = (Message) objectInputStream.readObject();
System.out.println(data.getValue);
} catch (IOException | ClassNotFoundException ex) {
disconnected(ex);
}
}
现在我需要发送不同的对象类型,但我找不到正确的方法来实现它。有人建议发送两条消息:第一条指示类型并准备服务器以投射第二条;
while (!socket.isClosed()) {
String type = null;
try {
if (type == null){
Message message = (Message) objectInputStream.readObject();
type = message.getType();
System.out.println(data.getValue);
} else {
//switch statement with possible types I can handle
//where I can have different casting
X message = (X) objectInputStream.readObject();
}
} catch (IOException | ClassNotFoundException ex) {
disconnected(ex);
}
}
在其他情况下,我看到了泛型的使用,但它们会导致很多问题,因为类型或转换被假定为不安全。
我想要一个更通用的版本,可以动态转换来自客户端的对象,反之亦然,像这样:
while (!socket.isClosed()) {
try {
Object data = objectInputStream.readObject();
//if object type is Message cast into a Message
//if object type is X cast into a X object
} catch (IOException | ClassNotFoundException ex) {
disconnected(ex);
}
}
也许我应该去做一些完全不同的事情,你有什么建议吗?
Object data = objectInputStream.readObject(); //if object type is Message cast into a Message //if object type is X cast into a X object
您正在寻找
instanceof
。例子:
Object data = objectInputStream.readObject();
if(data instanceof Message) {
Message m = (Message)data;
System.out.println("message type: "+m.type);
receivedMessage(m);
} else if(data instanceof X) {
X x = (X)data;
receivedX(m);
}
从 Java 14 开始还有一个速记语法:
Object data = objectInputStream.readObject();
if(data instanceof Message m) { // <- note the name m
System.out.println("message type: "+m.type);
receivedMessage(m);
} else if(data instanceof X x) { // <- and here
receivedX(m);
}
如果类型完全未知,你也可以使用
getClass()
获取类型,它返回一个Class
对象,你可以得到它的信息。 (注意null.getClass()
会抛出NPE)
Object data = objectInputStream.readObject();
if(data instanceof Message) {
receivedMessage((Message)data);
} else if(data == null) {
System.err.println("received null");
} else {
// don't know what it is, but it's not a Message
System.err.println("received unknown class "+data.getClass().getName());
}