Re: Confusion with templates, generics, and instanceof
Greg Boettcher wrote:
2. What I really wanted to know was whether you can test to see if an
object, o, belongs to the class specified by a type variable, T. The
condition (o instanceof T) doesn't seem to work. This was my main
reason for posting here, and it's too bad I picked a bad example for
it. Anyway, I am starting to think that this is impossible. If I'm
wrong, please let me know.
'instanceof' is run-time. Generics are compile-time.
One way, outlined in the Josh Bloch book chapter referenced upthread, is for a
class to keep a 'Class<T>' variable internally to run the check.
Another is to use a helper method with a 'T' argument and a cast its argument
from the caller.
private boolean isFoo( T arg )
{
...
}
public boolean isFoo( Object arg )
{
try
{
@SuppressWarnings( "unchecked" ) // catches CCE
T tA = (T) arg;
return isFoo( tA );
}
catch ( ClassCastException exc )
{
return false;
}
}
Untested, not even compiled.
Casting to a generic type raises a warning, which you can suppress as long as
you check for a 'ClassCastException' or otherwise guarantee the safety.
4. And, yes, I should probably read more of the official
documentation. I didn't this time because I'm under a time crunch.
So not knowing what you're doing makes you faster?
--
Lew