isInstance & instanceof - Why there's no generic way?

Ava410

New Member
I understand the usage & motive of both of these - isInstance is Runtime Equivalent of instanceOf.But , why do we have two ways?Why could not we have a generic implementation of instanceof keyword which caters to both the cases?For Example , this is the way these are used currently: 1)instanceof\[code\]public Collection<String> extract(Collection<?> coll) { Collection<String> result = new ArrayList<String>(); for (Object obj : coll) { if (obj instanceof String) { result.add((String) obj); } } return result;}\[/code\]2)isInstance\[code\]public <T> Collection<T> extract(Collection<?> coll, Class<T> type) { Collection<T> result = new ArrayList<T>(); for (Object obj : coll) { if (type.isInstance(obj)) { result.add((T) obj); } } return result;}\[/code\]So , my Question is why can't we have a generic implementation of instanceof operator that caters to the 2nd exmaple above as below? (i.e. Why can't it resolve the type at runtime?)\[code\]public <T> Collection<T> extract(Collection<?> coll, Class<T> type) { Collection<T> result = new ArrayList<T>(); for (Object obj : coll) { if (obj instanceof type) { result.add((T) obj); } } return result;}\[/code\]
 
Back
Top