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

一曲冷凌霜 提交于 2019-11-27 00:47:59
Hardcoded

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 recommend one):

if (view instanceof B)
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).

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

if (view instanceof B) {
    // this view is an instance of B
}

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.

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

If there is polymorphism such as checking SQLRecoverableException vs SQLException, it can be done like that.

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

Simply say,

ChildClass child= new ChildClass();
if(ParentClass.class.isAssignableFrom(child.getClass()))
{
    // do sth
    ...
}

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!