Generic implementation principle: type erasure

Type erasure

What is type erasure?
Type parameters only exist at compile time. At runtime, the Java virtual machine does not know about the existence of generics.

Examples:

import java.util.ArrayList;

public class ErasedTypeTest {
    public static void main(String[] args) {
        Class c1 = new ArrayList<String>().getClass();
        Class c2 = new ArrayList<Integer>().getClass();
        System.out.println(c1 == c2);//true,这里并不知道类ArrayList<String>和ArrayList<Integer>,只知道ArrayList
    }
}

Effects of type erasure:

Reference:
https://segmentfault.com/a/1190000020382440
https://segmentfault.com/a/1190000005179142

  • Generic types cannot be used as method overloads
public void testMethod(List<Integer> array) {}
public void testMethod(List<Double> array) {}    // compile error
  • Generic types cannot be used as real types
static <T> void genericMethod(T t) {
  T newInstance = new T();              // compile errror
  Class c = T.class;                    // compile errror
  List<T> list = new ArrayList<T>();    // compile errror
  if (list instance List<Integer>) {}   // compile errror
}

Guess you like

Origin www.cnblogs.com/JohnTeslaaa/p/12706786.html