File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics, compile/run time" Watch "Generics, compile/run time" New topic

Generics, compile/run time

David Sabate

Joined: Feb 25, 2013
Posts: 10
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,

Jelle Klap

Joined: Mar 10, 2008
Posts: 1951

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:
subject: Generics, compile/run time
It's not a secret anymore!