0

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

Oekel
  • 43
  • 9
  • `if(p.getClass().isInstance(Child.class))` or `if(Child.class.isInstance(p.getClass()))` is the same. like (1==(2-1)) or ((2-1)==1) – Angga Jun 19 '14 at 06:30
  • pClass.isInstance(child) return true means child is an instance of pClass – BlackJoker Jun 19 '14 at 06:31

1 Answers1

4

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).

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194