Eclipse says that the instanceof operation is not allowed with Type Parameter due to generic type eraser.
I agree that at runtime, no type information stays. But con
If you need T at runtime, you need to provide it at runtime. This is often done by passing the Class
class SomeClass {
final T t;
public SomeClass(Class 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 SomeClass of(Class tClass, T t) {
if(!tClass.isAssignableFrom(t.getClass()) throw new IllegalArgumentException("Must be a " + tClass);
return new SomeClass(t);
}
}
// doesn't compile
SomeClass intSomeClass = SomeClass.of(Integer.class, "one");
Class clazz = Integer.class;
// compiles with a warning and throws an IAE at runtime.
SomeClass intSomeClass = (SomeClass) SomeClass.of(clazz, "one");
// compiles and runs ok.
SomeClass intSomeClass = SomeClass.of(Integer.class, 1);