例如:
class A {
private List<B> list;
//todo get set
}
我怎么通过 A.class 获得 B.class
例如:
class A {
private List<B> list;
//todo get set
}
我怎么通过 A.class 获得 B.class
|
1
Field listField = A.class.getDeclaredField("list");
Type type = listField.getGenericType(); Class detailClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[0]; |
|
2
JAVA 就怕泛型,没有泛型的话楼上反射就可以,
泛型涉及类型擦除一般建议单独保存 type, |
|
xuanbgJul 1, 2021
3
只要一路泛型到底,就不需要知道具体类型。
|
|
ztcaoll222Jul 2, 2021
7
@Tuy #6 load json 可以使用 TypeReference
|
|
BrokenVnsJul 2, 2021
8
查你用的 JSON 库的文档,看看有没有提供泛型相关的支持。比如 Gson 会提供 TypeToken 。也可以去参考类似 GSON 等库的实现。
|
|
bthuluJul 2, 2021
10
改用 c#吧, 真泛型不擦除
|
|
siweipanccJul 2, 2021 via iPhone
11
你这是要重新实现 jackson?参照一下阿里的运行时 typeReference,直接抄过来也可以
|
|
eric96Jul 2, 2021
12
运行时是找不到的,泛型被擦除了,所以泛型只要保证编译时通过,代码就能跑起来。
|