java 泛型类型如何保留类型的信息的方式

https://www.baeldung.com/gson-typetoken-dynamic-list-item-type
https://stackoverflow.com/questions/43117731/what-is-type-typetoken

大意就是通过各种方式保留泛型的信息。有通过变量的方式,有通过继承的方式。

变量的方式就不说了,只是在构造函数那里处理泛型的传入,然后解析相应的值放到类变量中。

继承的方式这里说下,TypeToken是gson特有的,不过意思是相同的。

TypeToken<List<Student>> typeTokenForListOfStudents = new TypeToken<List<Student>>() {};

与上面的作用是相同的,都是为了留存泛型的信息


// 泛型基础类
class A<T> {};

// 子类
class B extends A<B> {};

// 使用的时候,使用B类即可,这样继承A的方法等需要类型信息的时候,都能通过`this.getClass()`来获取到。

// 使用例子:
B b1 = new B();

// 又或者是
A<String> a1 = new A<String>() {};

但是如果你想获取B extends A<B>中的<>里的类型的话,就需要使用以下代码来获取泛型的类型

Type superclass = this.getClass().getGenericSuperclass();
if (superclass instanceof ParameterizedType parameterized) {
    if (parameterized.getRawType() == A.class) {
        return parameterized.getActualTypeArguments()[0];
    }
}
posted @ 2025-07-21 16:08  星小梦  阅读(11)  评论(0)    收藏  举报