June 21, 2005

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

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!
    }
}
Next: Researching the interviewee
Previous: Now THAT is anti-tax