RandellK02
RandellK02

Reputation: 167

How to check for a class type and see if it implements an interface

I have an arrayList with a number of different objects including Log, Frog, Turtle, Rock etc. I would like to perform some action that only applies to the class types that implements and interface, IAction.

Is there something built in in Java that can do this? My attempt:

for(Object o : objectList){
    if(o.getClass instanceof IAction){ // doesnt work
        // doWork
    }
}

Upvotes: 2

Views: 57

Answers (1)

Bohemian
Bohemian

Reputation: 425448

You check the instance, not the class:

for (Object o : objectList){
    if (o instanceof IAction) { 
        // doWork
    }
}

Upvotes: 5

Related Questions