What does `instanceof` check to determine the types of objects?

I am using kryonet to send objects back and forth from server and client. There is a listener that runs whenever an object is received. The only way to define an instance of an object is to use:

if(object instanceof ClientLoginPacket){
    //Do stuff
}

      

I want to know what instanceof checks determine if an object is of a certain type or not. Does it check that the class exactly matches the whole code, does it check the variables and there names? Does it check imported packages as well? Any information you give me can help.

The reason I want to know this is because, as I am making the package, the code in the methods for the server is different from the client. For example, on my client to send packets, I do:

public void send(){
    Client.sendPacketTCP(this);
}

      

and on my server i do this:

public void send(){
    Server.sendPacketTCP(this);
}

      

+3


source to share


4 answers


My test results: Everything matters (variables, methods, package declarations, you name it!)

I don't understand why people say that this is inaccurate, it is actually too accurate for what I want to do, but I know what adjustments I need to make anyway.



Thanks everyone for the help!

0


source


instanceof is a jvm instruction, probably native code, but the spec says what it should do:

Instanceof



I really don't think it is checking the variable and its names, it's useless. It must traverse the class hierarchy until it can prove that it is some type: extends, implements, or is the same class

+6


source


According to the java docs , a isInstance#Object

method is the dynamic equivalent of a Java language instance operator.

This method tests whether the type represented by the specified class parameter can be converted to the type represented by this class object through an identifier conversion or through an extended reference conversion.

See the Java Language Specification, sections 5.1.1 and 5.1.4 for details .

+2


source


The reason I want to know this is because I am doing a package, the code in the methods for the server is different from the client.

I've never used Kryonet, but according to its documentation, this is exactly what you shouldn't be doing:

It is very important that the same classes are registered on both the client and the server, and that they are registered in the same order.

So ask yourself: why are you using different client-side and server-side classes? Could you find a "data-only" abstraction that would work on both sides and send just that?

+1


source







All Articles