One of those java features I should have known: class.isInstance()

lachoy on 2005-06-21T13:10:28

One of the few times I've written a piece of functionality and actually found it later: the isInstance() method of the Class class. It's useful when you're dealing with generic classes and therefore cannot use instanceof:

void ensureAllHaveParent( Collection c, Class parentClass ) {
    for ( Iterator it = c.iterator(); it.hasNext(); ) {
        Object o = it.next();
        if ( ! ( o instanceof parentClass ) ) ... // WRONG!
        if ( ! parentClass.isInstance( o ) )  ... // RIGHT!
    }
}

Posted from cwinters.com; read original