How to check if a subclass is an instance of a class at runtime?

In the Android app test suite, I have a class like this, where B is the view:

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

I now have a list of view objects that can contain objects of A , but in this case I don’t care if they are subclasses or “instances” of B I would 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 if encounters object A , it does not evaluate "instance B ". Is there a way to do isSubclassOf or something else?

+55
java instanceof subclass
Mar 09 '10 at 15:46
source share
7 answers

You should carefully read the API for these methods. Sometimes you can get confused easily.

It is either:

 if (B.class.isInstance(view)) 

The API says: determines that the specified object (parameter) is compatible with the destination with the object represented by this class ( class object called by method in)

or

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

The API says: determines whether the class or interface represented by this class object is either the same or the superclass or the superinterface of the class or interface represented by the specified class parameter

or (without reflection and recommended):

 if (view instanceof B) 
+131
Mar 10 '10 at 8:28
source share
 if(view instanceof B) 

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

+19
Mar 09 '10 at 15:49
source share

Maybe I missed something, but that would not be enough:

 if (view instanceof B) { // this view is an instance of B } 
+8
Mar 09 '10 at 15:49
source share

Class.isAssignableFrom() - works for interfaces Class.isAssignableFrom() . If you do not want this, you will need to call getSuperclass() and test until you reach Object .

+6
Mar 09 '10 at 15:51
source share

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

+2
Mar 09 '10 at 15:49
source share

If polymorphism exists, such as checking for SQLRecoverableException and SQLException, you can do so.

 try { // sth may throw exception .... } catch (Exception e) { if(SQLException.class.isAssignableFrom(e.getCause().getClass())) { // do sth System.out.println("SQLException occurs!"); } } 

Just say

 ChildClass child= new ChildClass(); if(ParentClass.class.isAssignableFrom(child.getClass())) { // do sth ... } 
0
Jul 31 '13 at 2:16
source share

I have never used this, but I will try view.getClass().getGenericSuperclass()

-one
Mar 09 '10 at 15:51
source share



All Articles