Check if an object is an instance of any of the class lists (Android)… here is a solution to the problem.
Check if an object is an instance of any of the class lists (Android)
I’ve been working on it for a while and while it’s not important, I’m wondering if there’s a clever way (maybe 1 line) that can be used to check if an object is an instance of any of several objects such as a class, I can do that :
if(anObject instanceof Pupil){ ... }
else if(anObject instanceof Teacher) { ... }
And so on and so forth. Is there a better way to do this, or is this as good as I want?
Solution
Make a Collection
Class object of your choice and….
if(myClasses.contains(obj.getClass())) {
obj is one of the classes I care about, so do something
}
Of course, this won’t help if you’re going to convert obj
afterwards (but as I said in my comment, this suggests a design issue).