Java – why is “t instanceof T” not allowed, where t is a type parameter and t is a variable?
•
Java
Eclipse indicates that the instanceof operation is not allowed for the type parameter due to the generic eraser
I agree that type information will not be retained at runtime However, consider the general declaration of the following classes:
class SomeClass<T>{
T t;
SomeClass(Object o){
System.out.println(o instanceof T); // Illegal
}
}
At run time, t will not appear! However, if I instantiate this class of type integer, the corresponding object will have the field t
So why can't I use t to check the type of variable, which can be replaced by integer at run time And I actually do things like "O instance of integer"
Under what circumstances does allowing instanceof with type parameters cause a failure and prohibit it?
Solution
If t is required at runtime, it needs to be provided at runtime This is usually done by passing class < T > T must be
class SomeClass<T> {
final T t;
public SomeClass(Class<T> tClass,T t) {
if(!tClass.isAssignableFrom(t.getClass()) throw new IllegalArgumentException("Must be a " + tClass);
this.t = t;
}
private SomeClass(T t) {
this.t = t;
}
public static <T> SomeClass<T> of(Class<T> tClass,T t) {
if(!tClass.isAssignableFrom(t.getClass()) throw new IllegalArgumentException("Must be a " + tClass);
return new SomeClass(t);
}
}
// doesn't compile
SomeClass<Integer> intSomeClass = SomeClass.of(Integer.class,"one");
Class clazz = Integer.class;
// compiles with a warning and throws an IAE at runtime.
SomeClass<Integer> intSomeClass = (SomeClass<Integer>) SomeClass.of(clazz,"one");
// compiles and runs ok.
SomeClass<Integer> intSomeClass = SomeClass.of(Integer.class,1);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
