Search code examples
javaidentityproofisinstance

What is the right direction of using "*.isInstance"?


I am confused every time I read the Java Documentation again to that. So please try to help me in your own words.

List<Parent> list = new ArrayList<Parent>();
//Child extends Parent...
list.add(new Child());
...
...
for(Parent p: list){
    if(p.getClass().isInstance(Child)){
            Child c = (Child) p;
            c.execFuncNonExistingInParent();
    }
}

Just wanna proof the Objects inheritances from Parent, to avoid Cast Problems.

if(p.getClass().isInstance(Child.class))

or

if(Child.class.isInstance(p.getClass()))

Greatings Oekel


Solution

  • That's not checking what you want to check either way round. You want:

    if (Child.class.isInstance(p))
    

    That's equivalent to:

    if (p instanceof Child)
    

    ... except you can specify the class to check dynamically, rather than it being fixed at compile-time. If you do know the class at compile-time (as in your example) then just use the instanceof operator instead.

    For isInstance, it's easy to tell which way round it goes, once you've remembered it as being equivalent to instanceof, because of the signature:

    // In Class
    public boolean isInstance(Object obj)
    

    You want the equivalent of obj instanceof clazz, where obj can be any object reference, and clazz must be a class... so you really have to call it as clazz.isInstance(obj).