IsInstance & instanceof - Why is there no general way?

I understand that the use and motive of both of them - isInstance - is the equivalent of the instanceOf instance time. But why do we have two ways? Why can't we have a generic instanceof keyword implementation that is suitable for both cases?

For example, so they are currently used:

1) InstanceOf

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;
}

2) isInstance

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;
}

So my question is: why can't we have a generic implementation of the instanceof operator that satisfies the second example above, as shown below? (i.e. why can't it resolve the type at runtime?)

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;
}
+5
source share
1 answer

Some background:

  • The keyword / syntax instanceofwas in Java from Java 1.0 (IIRC).

  • Class.isInstance Java 1.1 ( javadoc).

  • Java 1.5 (aka 5.0) , , .


instanceof <expr> 'instanceof' <type>. , <expr> 'instanceof' <type> | <expr>. :

  • . ( , , .)

  • . , , , Something. , obj instanceof Something ? obj instanceof Something.class?

, "" . , . , .


, Java . ( !). , , . , Java ... .

( " " Java 9, , , , , , . , , .)


1) , ? , .

. , ; .. , . - ( ), , .

2) , ( )

, , , , , .

? ""... , , , , "".

+4

All Articles