一、类型擦除
public class A<T> {
private T value;
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
}
//编译后
public class A
{
private Object value;
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
}
所以,运行时进行类型查询的时候使用下面的方法是错误的
@Test
public void test3() {
ArrayList<String> arrayList=new ArrayList<>();
if (arrayList instanceof ArrayList<String>) {
//illegal generic type instanceof
System.out.println("ture");
}
}
二、类型擦除时机
@Test
public void test1() {
A<String> stringA = new A<>();
A<Integer> integerA = new A<>();
System.out.println(stringA.getClass()==integerA.getClass());
}
//打印
true
说明泛型的擦除是在编译前,jvm会将其看做同一个普通类Object进行处理
三、类型检查时机
@Test
public void test3() {
ArrayList<String> arrayList=new ArrayList<String>();
arrayList.add("123");
arrayList.add(123);//编译错误
}
先检查泛型类型,再擦除,再编译,保证我们只能使用泛型变量限定的类型进行操作。
@Test
public void test2() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
ArrayList&l