简体   繁体   English

instanceof不适用于“或”

[英]instanceof doesn't work with “or”

I'm working on a web project with Java. 我正在使用Java进行Web项目。

My colleague has finished the socket part, including object serialization and deserialization. 我的同事已经完成了套接字部分,包括对象序列化和反序列化。

What I need to do is to develop the classes that would be serialized and deserialized to send and receive them. 我需要做的是开发将被序列化和反序列化以发送和接收它们的类。

The sequence diagram is simple: 序列图很简单:

  • the client sends a string to the server 客户端向服务器发送一个字符串
  • the server create an object with the received string 服务器使用接收到的字符串创建一个对象
  • the server sends the object to the client 服务器将对象发送给客户端

I have now two kinds of objects: 我现在有两种对象:

class T1{public int i1 = 1;}
class T2{public int i2 = 2;}
//both classes have implemented Serializable and override toString

And I do things as below: 我做以下事情:

Object obj = class.forName(strFromClient).newInstance();
if(obj instanceof T1 || obj instanceof T2)
{
    // send obj to client with my colleague's method
    send(obj);
}

The client can receive successfully the obj of type of T1 , the client can System.out.println(obj) and get 1 . 客户端可以成功接收T1类型的obj,客户端可以通过System.out.println(obj)获得1
To my surprise, when I do the same thing for T2 , it doesn't work. 令我惊讶的是,当我对T2做同样的事情时,它不起作用。 When the client try to System.out.println(obj) , a 0 is shown whereas I'm expecting a 2 . 当客户端尝试使用System.out.println(obj) ,显示为0 ,而我期望为2 I also try to add a String into T2 and the client get an NullException , meaning that the string in the received obj is null . 我还尝试将String添加到T2中,并且客户端获得NullException ,这意味着接收到的obj中的字符串为null

I don't quite understand why but if I change my code like this, everything will be fine: 我不太明白为什么,但是如果我这样更改代码,一切都会好起来的:

Object obj = class.forName(strFromClient).newInstance();
if(obj instanceof T1)
{
    // send obj to client with my colleague's method
    send(obj);
}
else if(obj instanceof T2)
{
    // send obj to client with my colleague's method
    send(obj);
}

I did a test using the following code: 我使用以下代码进行了测试:

Object x = 1; // afterwards = ""

if (x instanceof String || x instanceof Integer) {
    System.out.println("Hurray!");
}

In both cases: x = 1 or x = "" the string Hurray! 在两种情况下: x = 1x = ""字符串Hurray! was printed. 被印刷了。 Hence I guess your obj is neither of type T1 nor of type T2 . 因此,我想您的obj既不是T1类型也不是T2类型。

i think your problem is - T1 and T2 value you receive there are null , 我认为您的问题是-您收到的T1和T2值为null,

in only that case the condition will not get validated . 只有在这种情况下,条件才能得到验证。

Please debug and check the value of T1 and T2 you receive in the step. 请调试并检查在该步骤中收到的T1和T2的值。

You can use this code - and add null checks before instance of 您可以使用此代码-并在的实例之前添加null检查

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM