379

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

For example: my problem can be reproduced in Java as following-

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?

3
  • 7
    If you really feel you need a switch you could hash the class name to an int and use that, watch out for possible clashes though. Adding as comment rather than an answer as I don't like the idea of this actually been used. Maybe what you really need is the visitor pattern. Commented Apr 7, 2011 at 10:13
  • 1
    As of java 7 you could even switch on the fully qualified class name to avoid such hash clashes as @vickirk pointed out, but it's still ugly. Commented Jun 2, 2014 at 16:14
  • It is possible with the classname as an Enum value Commented Mar 27, 2019 at 15:26

31 Answers 31

1
2
-6

If you want to avoid the verbosity of if(){} else if{}, you may consider switching this single file to kotlin and use the switch-like when expression in combination with is operator.

In any case Kotlin and java files can co-exist in a project and result in a jar that can run in JVM.

when (this) { //switch-like statement in kotlin supporting class-pattern-matching and smart casts via `is` operator. is A -> doA() is B -> doB() is C -> doC() } 
Sign up to request clarification or add additional context in comments.

Comments

1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.