Issue
So I'd like to know an easy way of switching over valid types in Java, such as below:
(I know this doesn't compile, but I want this functionality)
public void put(Object obj) {
if (obj instanceof Integer) {
} else if (obj instanceof String) {
} else if (obj instanceof Boolean) {
} else if (obj instanceof List<String>) {
} else if (obj instanceof Map<String, String>) {
}
}
Solution
The simply answer is: there is no switching on "type" in Java. In contrast to languages such as Scala, Java doesn't have an almost magic "pattern matching" feature.
When you really need to do that: figure the specific type of an Object instance, to then do different things based on the true nature of the object, such an if/else cascade is one of few choices.
One alternative is to use a map, like Map<Class<?>, Consumer<?>)
or something alike. In other words: you (upfront) create a map that knows a method to call for different classes, and then do obj.getClass()
to see if your map knows about that class. But that mechanism isn't very robust, as it only uses equals()
for the class instances.
Beyond that: there are only very few selected use cases where such kind of "type switching" makes sense. Typically, you approach this problem ... by stepping back, looking at the real underlying problem and designing a completely different solution.
Answered By - GhostCat
Answer Checked By - Timothy Miller (JavaFixing Admin)