Needs to understand internal implementation of Generics in java

I am very confused about internal implementation of generic.
I read lot of articals also and most of them says “Type parameter” is removed while generating .class file.
like e.g.

class A<T> {
 public void add(T t1){
    ....
 }
}

in .class file, above code will be

class A {
 public void add(Object t1){
    ....
 }
}

I have a 3 question:

Q 1)

A<String> a1 = new A<String>()
      a1.add(10);

Type parameter already removed in .class file then how compiler gives compilation error.

Q 2) Let say I write below java file:

 class B {
   public void add(Object t1){
      ....
   }
  }

And Now I am creating instance like this

B<String> b1 = new B<String>();

It will gives compile time error. But If I create instance of class A same as above then it is allows
Means at generics (type parameter) information available at run time also.

Q 3) If type information not available in .class file :

class C <T, X> {
  public void add(T t1, X x1){
     .....
  }
}

in .class file, code like:

class C {
  public void add(Object t1, Object x1){
     .....
  }
}

Now create an instance

C<String, Integer> c1 = new C<String, Integer>();

then how compiler map t1 as String and x1 as integer.

Source: java

Leave a Reply