0

Is there a way to decide whether a particular interface is an instanceof another interface with a switch statement?

 MainInterface inter = //load interface

 switch (inter) {
        case instanceof Interface1:
            Interface1 inter1 = (Interface1) inter;
            //execute methods of inter1
        case instanceof Interface2:
            Interface2 inter2 = (Interface2) inter;
            //execute methods of inter2
    }

Thanks for your help.

TryHard
  • 359
  • 2
  • 3
  • 15
  • 1
    Does this answer your question? [Is it possible to use the instanceof operator in a switch statement?](https://stackoverflow.com/questions/5579309/is-it-possible-to-use-the-instanceof-operator-in-a-switch-statement) – Ivar Feb 06 '20 at 09:19
  • Not yet, but it's being considered. There is also the deconstructing `if(obj instanceof Interface1 i1) {` that is being considered and would at least make if / else if less awkward – kumesana Feb 06 '20 at 09:19
  • no, not directly. you could use an enum value, though, that you calculate from the interface depending on its type. – Curiosa Globunznik Feb 06 '20 at 09:19
  • @Ivar unfortunately this doesn't help me :( – TryHard Feb 06 '20 at 09:25
  • @kumesana Yeah thats basically my current solution but it looks ugly and want to put it in a switch statement – TryHard Feb 06 '20 at 09:26
  • 2
    @TryHard Non of the 23 answers? – Ivar Feb 06 '20 at 09:27
  • You could make a Map, Consumer> that you fill with the interfaces you're interested in and the actions you want to do for each. – kumesana Feb 06 '20 at 09:27
  • @güriösä I found that solution before but it seems to be more effort. I guess theres no way to change my implementation. – TryHard Feb 06 '20 at 09:28

2 Answers2

2

Sadly, this is not possible, as stated in oracle's documentation: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types [...], the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer [...].

Some ways of getting around this would be to either use if-else statements or to implement subtype polymorphism, as Ivar suggested.

bw2801
  • 321
  • 2
  • 8
  • 15
1

It is not possible to do it with switch case statement. You have to use if statements.

MainInterface inter = null;

if (inter instanceof Interface1) {
    Interface1 inter1 = (Interface1) inter;
    // execute methods of inter1
} else if (inter instanceof Interface2) {
    Interface2 inter2 = (Interface2) inter;
    // execute methods of inter2
}
Kristóf Göncző
  • 382
  • 1
  • 5
  • 16