wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics, compile/run time Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics, compile/run time" Watch "Generics, compile/run time" New topic
Author

Generics, compile/run time

David Sabate
Greenhorn

Joined: Feb 25, 2013
Posts: 8
The following code will not compile



The explanation says the parameter E only exist at compile time. At runtime, the type information is not available, and the instanceof operator wouldn't make sense.
Even with that explanation I'm not too sure I understand how it works, can someone help?

Many thanks,
David
Jelle Klap
Bartender

Joined: Mar 10, 2008
Posts: 1753
    
    7

Yes, this is due to a process known as type erasure performed by the compiler.
Basically* the compiler strips out all generic information from the source code as it compiles the binary .class files that are used at runtime. This means that type generic type E in your example is gone after the compiler has done it's job, but that would leave the instanceof check broken, because it uses the type E on the right hand-side. The compiler recognizes this situation and generates an error that prevents you from using generic types in such a way.


*It's a bit more complicated than that actually.


Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Generics, compile/run time
 
Similar Threads
reference casting from Mugal
instanceof operator
Khalid Mughal and instanceof operator
instanceof?
Aren't Collection and AbstractMap peers? what's the common subclass?