Monday, March 9, 2009

Type Erasure  


                     When a generic type is instantiated, the compiler translates those types by a technique called type erasure — a process where the compiler removes all information related to type parameters and type arguments within a class or method. Type erasure enables Java applications that use generics to maintain binary compatibility with Java libraries and applications that were created before generics.

public class MyClass {
  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 class WarningDemo {
  public static void main(String[] args){
  Box bi;
  bi = createBox();

  static Box createBox(){
  return new Box();
Recompiling with -Xlint:unchecked reveals the following additional information: warning: [unchecked] unchecked conversion
found : Box
required: Box
  bi = createBox();
1 warning

What next?

You can also bookmark this post using your favorite bookmarking service:

Related Posts by Categories

0 comments: to “ Type Erasure

Extension Factory Builder