Is there some syntax (other than a series of if statements) that allows for the use of a switch statement in Java to check if an object is an instanceof a class? I.e., something like this:
switch (object) {
case instanceof SecondObject:
break;
case instanceof ThirdObject:
break;
}
Sidenote: I recognize that as a design pattern, checking against instanceof and making decisions based on it is not as preferable as using inheritance. To give some context why this would be useful to me, here's my situation:
I'm working on a project that involves a kryonet client/server. For communication over KryoNet, you pass objects that it serializes using kryo. Anything added to the object increases the size of these packets,1 so to minimize the network traffic, you keep these objects as light weight as possible. When you receive a packet, you need to know what to do with it, so I'm making this determination based on what type of packet object the passed object is an instanceof. This approach is the same undertaken in the examples included with Kryonet's distribution. I'd love to clean up the hideous class that translates these packets into action, and figure a switch statement would at least make it look moderately more organized.
1As I wrote the statement above, I had doubts about whether what I was saying was accurate. The answer below seems to disagree:
Methods don't add anything to the runtime size of an object. The method code is not transmitted, and nothing about the methods requires any representation in an object's state. This is not a sound reason for instanceof testing, etc.
I guess the real issue is I don't know what happens under the hood for Kryo to serialize an object and I was nervous to do anything that increased the bandwidth. Your answers have inspired me to do it with inheritance and add the appropriate methods to the objects. So thank you!