x7041
x7041

Reputation: 39

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

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.

Upvotes: 2

Views: 3736

Answers (2)

user11595728
user11595728

Reputation:

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

Upvotes: 1

Michał Krzywański
Michał Krzywański

Reputation: 16940

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
    }
}

Upvotes: 5

Related Questions