views:

456

answers:

7

In an android app test suite I have a class like this where B is a view:

public class A extends B {
... etc...
}

now I have a list of view objects which may contain A objects but in this case I only care if they're subclasses or "instances of" B. I'd like to do something like:

ArrayList<View> viewList = getViews();
Iterator<View> iterator = viewList.iterator();
while (iterator.hasNext() && viewList != null) {
    View view = iterator.next();
    if (view.getClass().isInstance(B.class)) {
        // this is an instance of B
    }
}

The problem is that when the "if" encounters an A object it doesn't evaluate to an "instance of B". Is there a way to do isSubclassOf or something?

Thanks.

+5  A: 
if(view instanceof B)

This will return true if view is an instance of B or the subclass A (or any subclass of B for that matter).

Kris
+3  A: 

Maybe I'm missing something, but wouldn't this suffice:

if (view instanceof B) {
    // this view is an instance of B
}
Joachim Sauer
+1  A: 

It's the other way around: B.class.isInstance(view)

nanda
A: 

I've never actually used this, but try view.getClass().getGenericSuperclass()

chama
+2  A: 

Class.isAssignableFrom() - works for interfaces as well. If you don't want that, you'll have to call getSuperclass() and test until you reach Object.

Michael Borgwardt
This seems to work, thanks.
I am amused
+2  A: 

You have to read the API carefully for this methods. Sometimes you can get confused very easily.

It is either:

if (B.class.isInstance(view))

API says: Determines if the specified Object (the paramter) is assignment-compatible with the object represented by this Class (The class object you are calling the method at)

or:

if (B.class.isAssignableFrom(view.getClass()))

API says: Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter

or (without reflection and the recommend one):

if (view instanceof B)
Hardcoded
+1  A: 

From Effective C++, by Scott Meyers :

"Anytime you find yourself writing code of the form "if the object is of type T1, then do something, but if it's of type T2, then do something else," slap yourself.

Could you not use an overridden method instead? Or perhaps something like the visitor pattern.

It's for a test case so the code is not actually in the production app, it's to test to make sure things are using the right classes :)
I am amused