Is it possible to use the instanceof operator in a switch statement?

olidev picture olidev · Apr 7, 2011 · Viewed 254.1k times · Source

I have a question of using switch case for instanceof object:

For example: my problem can be reproduced in Java:

if(this instanceof A)
    doA();
else if(this instanceof B)
    doB();
else if(this instanceof C)
    doC():

How would it be implemented using switch...case?

Answer

jmg picture jmg · Apr 7, 2011

This is a typical scenario where subtype polymorphism helps. Do the following

interface I {
  void do();
}

class A implements I { void do() { doA() } ... }
class B implements I { void do() { doB() } ... }
class C implements I { void do() { doC() } ... }

Then you can simply call do() on this.

If you are not free to change A, B, and C, you could apply the visitor pattern to achieve the same.