Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics, compile/run time

 
David Sabate
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic