Re: what do you mean I can't (someObj instanceof MyGenericType) ?
Sideswipe wrote:
if(T instanceof arg) ... // compile error
arg is a variable not a typename.
if(T.class.isAssignableFrom(arg.getClass())) // compile error
What is 'T.class'? At runtime, the type argument is statically compiled
into the class file.
var = (T)arg;
Is this even legal?
Is this better?
No. Not by a long shot.
When one needs to work with generics, one ends up working with Class
objects a lot. Your class again:
class C<T> implements I {
private Class<T> tClass;
public C(Class<T> tClass) {
this.tClass = tClass;
}
public void method1(Object arg) {
T var = tClass.cast(arg);
// [...]
}
}
Even better would be to make your interface generic as well, so that
less runtime checks would be needed.
Java Generics are NOT C++ Templates. Only one class file is ever used,
so the types of type arguments are erased to the tightest bound known,
which is generally Object. Because each invocation of T is more or less
are equivalent to Object (or the relevant type erasure), constructs like
T[], T.class, (T), and instanceof T are prohibited.
For more information, read Sun's generics information (look at one of
the more recent generics threads for the link; I don't know it off the
top of my head).
--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth