Why does instanceof seem to work in a static generic function sometimes?
- by michael
Greetings. This is my first post in this site.
I thought that because of type erasure, one could not expect the following code to compile, and indeed, it did not compile on an earlier version of Eclipse. My understanding was that instanceof was a run-time operator and could not know about the generic type which would be, by run-time, compiled away:
public static <E extends Comparable<? super E>>
void SampleForQuestion(E e)
{
if ( !(e instanceof String) )
System.out.println("I am not a String");
else
System.out.println("I am a String");
}
However, I was surprised to see that one of your threads actually included some code like this in an answer, and my latest Eclipse (Galileo on Windows with JVM 1.6 rev 20) is perfectly happy with it -- and it works, too. (I did notice that someone said it worked on Eclipse but not in another IDE/JDK in that thread, but don't remember the specifics.)
Can someone explain why it works, and more importantly, because I have to guide my students, whether it should be expected to work in the future.
Thank you. (I hope the code formatting comes through correctly - it looks indented correctly from my perspective and there are no tabs.)