mercredi 22 mars 2017

instanceof doesn't work with "or"

I'm working on a web project with Java.

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.
To my surprise, when I do the same thing for T2, it doesn't work. When the client try to System.out.println(obj), a 0 is shown whereas I'm expecting a 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.

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





Aucun commentaire:

Enregistrer un commentaire