Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 396
olidev Avatar asked Apr 07 '11 10:04

olidev


People also ask

What types can be used in a switch statement?

A switch works with the byte , short , char , and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character , Byte , Short , and Integer (discussed in Numbers and Strings).

What is the use of Instanceof operator?

The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. objectName instanceOf className; Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .

Can I use Instanceof with interface?

instanceof can be used to test if an object is a direct or descended instance of a given class. instanceof can also be used with interfaces even though interfaces can't be instantiated like classes.

What type of operator is Instanceof?

instanceof is a binary operator we use to test if an object is of a given type. The result of the operation is either true or false. It's also known as a type comparison operator because it compares the instance with the type. Before casting an unknown object, the instanceof check should always be used.


2 Answers

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.

like image 115
jmg Avatar answered Sep 23 '22 20:09

jmg


if you absolutely cannot code to an interface, then you could use an enum as an intermediary:

public A() {      CLAZZ z = CLAZZ.valueOf(this.getClass().getSimpleName());     switch (z) {     case A:         doA();         break;     case B:         doB();         break;     case C:         doC();         break;     } }   enum CLAZZ {     A,B,C;  } 
like image 25
Nico Avatar answered Sep 20 '22 20:09

Nico