• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

type erasure in java generic

 
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
in java tutorial, it says the following:

public class MyClass<E> {
public static void myMethod(Object item) {
if (item instanceof E) { //Compiler error
...
}
E item2 = new E(); //Compiler error
E[] iArray = new E[10]; //Compiler error
E obj = (E)new Object(); //Unchecked cast warning
}

public E getE ()
{
//....
}
}

if E is erased, why method getE does not cause compiler error, instanceof cause a compiler error?
 
Ranch Hand
Posts: 230
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There's a lot that goes on with type erasure, and there is a good reference guide here http://www.angelikalanger.com/GenericsFAQ/FAQSections/TechnicalDetails.html#FAQ001. But the reason instanceof E fails is because that is evaluated at runtime, not at compile time (this also applies for some of the other errors you're seeing). The java compiler (as part of the compilation process) removes the type from the getE method (I believe its compiled version actually just returns Object), however, during compilation it can validate that it is used being properly (i.e. assigned to the correct type of variable) - there are exceptions to this rule, such as invoking via reflection but we won't worry about that now.
 
reply
    Bookmark Topic Watch Topic
  • New Topic