Check if some object is instance of some class in a list

x7041 :

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.

SDJ :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=127668&siteId=1