简体   繁体   English

如何检查类类型并查看其是否实现了接口

[英]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 . 我有一个arrayList,其中包含许多不同的对象,包括LogFrogTurtleRock等。我想执行一些仅适用于实现和接口的类类型IAction

Is there something built in in Java that can do this? 是否有Java内置的东西可以做到这一点? My attempt: 我的尝试:

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

You check the instance, not the class: 您检查实例,而不是类:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM