泛型类型擦除

xiaoxiao2021-02-28  114

1、关于类型擦除 使用了泛型的代码在运行期间相关的泛型参数的类型会被擦除,无法在运行期间获知泛型参数的具体类型(所有的泛型类型在运行时都是Object类型)

/** * 使用了泛型的代码在运行期间相关的泛型参数的类型会被擦除,无法在运行期间获知泛型参数的具体类型(所有的泛型类型在运行时都是Object类型) * 编译时进行了类型擦除,导致两个函数定义一模一样,编译报错 */ public class TestErasure { public void test(List<String> strList){ System.out.println("test1"); } public void test(List<Integer> iList){ System.out.println("test2"); } }

进一步测试

// 简单测试 Integer i = new Integer(0); System.out.println(i.getClass()); List<Integer> iList = new ArrayList<Integer>(); System.out.println(iList.getClass()); String str = new String("123"); System.out.println(str.getClass()); List<String> strList = new ArrayList<String>(); System.out.println(strList.getClass()); // 测试擦除 System.out.println(iList.getClass() == strList.getClass() && iList.getClass().equals(strList.getClass())); // 结果为true

输出结果

class java.lang.Integer class java.util.ArrayList class java.lang.String class java.util.ArrayList true

2、可能问题&应用场景 使用Gson进行Json和Java对象之间的转化,对于包含泛型的类的序列化和反序列化Gson也提供了很好的支持。 对于泛型擦除问题,Gson通过借助TypeToken类来解决这个问题。

转载请注明原文地址: https://www.6miu.com/read-55356.html

最新回复(0)