Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

test and trust Class.isInstance or try and catch Class.cast ?

843793May 1 2009 — edited May 19 2009
I found this related thread, with no answer to my question.

In the below code, there is a certain level of redundancy in that I am checking that I can do the Class.cast() prior to doing it, via Class.isInstance().

I can either omit the isInstance() check and just count on cast() throwing an exception, or I can ignore the ClassCastException (do nothing in the catch block, as shown below).

Which is better? Is it faster if I just omit the instance check and let cast() detect the errors? Is there a style convention here?
    protected <T extends ParentClass> List<T> getItemsOfType(Class<T> clazz){
        List<T> retval = new ArrayList<T>();
        
        for(ParentClass t : items.values()){
            if(clazz.isInstance(t)){
                try{
                    retval.add(clazz.cast(t));
                }
                catch(ClassCastException cce){
                    // should never happen
                }
            }
        }
    }
Thanks for your time
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 16 2009
Added on May 1 2009
5 comments
371 views