I was going through TypeErasure topic at http://download.oracle.com/javase/tutorial/java/generics/erasure.html which says
that compiler removes all information related to type parameters and type arguments within a class or method.
Now considering the code below
public class Box<T> {
private T t; // lineA, T stands for "Type"
public void add(T t) { // lineB
this.t = t; // lineC
}
public T get() { // lineD
return t; // lineE
}
}
Now inside main method I have below code snippet
Box<String> box1 = new Box<String>(); // line1
box1.add("Scott"); // line2
String s1tr=box1.get(); // line3
Box<Integer> box2 = new Box<Integer>(); // line4
box2.add(1); // line5
Integer k=box2.get(); // line6
Now in above code (in Box class and main method) what are the changes compiler will make and at which line?
As the link says that compiler removes all information related to type parameters and type arguments within a class or method, when compiler
will compile Box class, will it remove all T,<String>,<Integer> occurences from Box class and main method respectively? If yes, what will be the compiled code after Removing T?
Type erasure happens at compile time. Java compiler removes those generic type information from source and adds casts as needed and delivers the byte code. Therefore the generated byte code will not have any information about type parameters and arguments. It will look like a old java code without generics. There is no way to determine the value of T at runtime, because that information is removed before the code is compiled.