2

So, I want to have a List of types, then loop through the List and check if an Object is instance of the type in that list.

This is how I would imagine it to work, but that is no Java syntax. Type1.class also doesn't work

List<Object> types = new ArrayList();
types.add(Type1);
types.add(Type2);

for (Object type : types) {
    if (someObject instanceof type) {
        doSomething();
    }
}

or the same thing with List<Class> or something like that

this clearly doesn't work, but I dont know whats the best way to do it. Of course I could just hardcode every Object I want to check, but that doesn't seem that elegant.

x7041
  • 39
  • 1
  • 3
  • Why is your types list a list of `Object` rather than `Class`? `Class` has an `isInstance` method that does exactly what `instanceof` does. – RealSkeptic Jun 23 '19 at 11:18
  • 8
    This sort of construct almost always has a "code smell", and quite often there are better and cleaner ways to achieve the end result that you desire. You may wish to tell more about the details of this end result rather than how you're trying to achieve it. – Hovercraft Full Of Eels Jun 23 '19 at 11:21

2 Answers2

5

From the Java docs :

In Java instances of the Class class represent classes and interfaces in a running Java application.

You could use Class::isInstance method to determine if object is instance of given type and then apply processing based on this evaluation:

List<Class<?>> types = new ArrayList<>();
types.add(String.class);
types.add(Integer.class);

String someObject = "someString";

for (Class<?> type : types) {
    if (type.isInstance(someObject)) {
         // do smoething
    }
}
Michał Krzywański
  • 15,659
  • 4
  • 36
  • 63
1

These kinds of requirements call for the use of reflection. There is a class in Java meant to represent the type of an object: class Class. Instances of that class effectively represent the types of objects. So you could do:

List<Class<?>> types = new ArrayList<>();
types.add(Type1.class);
types.add(Type2.class);

for (Class<?> type : types) {
    if (type.isAssignableFrom(someObject.getClass())) {
        doSomething();
    }
}

Note that in this situation it's important to know whether you want to check if your target object has exactly the same type as a type in a list, or can be assigned to the type in the list. The code sample covers the second option because it's closer to the original intent. If you need an exact match, you would do:

object.getClass() == type;

See also Class.isInstance vs Class.isAssignableFrom

SDJ
  • 4,083
  • 1
  • 17
  • 35
  • 5
    `==type` is *not* the same as `instanceof`. The `instanceof` operator returns true when your object has an is_a relation to the class - that is, if it is a subclass, or a subclass of a subclass, it still returns true. – RealSkeptic Jun 23 '19 at 11:20
  • 2
    [michalk's (and RealSkeptic's) `isInstance`](https://stackoverflow.com/a/56723386/157247) makes more sense here. – T.J. Crowder Jun 23 '19 at 11:26