Can you discover at runtime what class <T> is?
I think I already know the answer to this is "it can't be done" but I need to ask first before giving up and trying something different.
I've got some code which I'm writing with generics. However I have got one of the VERY rare cases where casting is still reqired. What makes this worse is that the one time I must cast in the eintire program is within a generic function. I'd hoped to be able to catch and handle the possible ClassCastException from within the same function.
Now I tried this:
Code:
class Foo {
static <T> T bar() {
try {
Object x;
//... some code that puts an object in x
T y = (T) x;
return y;
}
catch (ClassCastException e) {
// Handle what happens if x is not a T.
}
}
}
Annoyingly this code did not generate a ClassCastException at all and only generated it when the returned object was placed into a non-generic variable.
If I can get a Class object for T from within my function I can call isAssignableFrom to check this first and prevent the exception entirely. But I can't find a way to get this class object without being actually passed one.
All suggestions welcome.
Thanks
Signature
Please use: [ code ][/ code ] tags and reasonably correct tabbing. They really help us read your code
End Signature