Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 698
iamamused Avatar asked Mar 09 '10 15:03

iamamused


People also ask

Is there a way to check if a class is a subclass of another class?

Python issubclass() is built-in function used to check if a class is a subclass of another class or not. This function returns True if the given class is the subclass of given class else it returns False . Return Type: True if object is subclass of a class, or any element of the tuple, otherwise False.

How do you check if a class is an instance of a class?

Use the instanceof operator to check if an object is an instance of a class, e.g. if (myObj instanceof MyClass) {} . The instanceof operator checks if the prototype property of the constructor appears in the prototype chain of the object and returns true if it does.

Does Instanceof check subclass?

By default instanceof checks if an object is of the class specified or a subclass (extends or implements) at any level of Event.


1 Answers

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 parameter) 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 recommended one):

if (view instanceof B) 
like image 127
Hardcoded Avatar answered Sep 19 '22 18:09

Hardcoded