如何获取列表包含的元素类? [英] How to Get class of Elements that List Contains?

查看:426
本文介绍了如何获取列表包含的元素类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的列表:

private List<T> myList = new ArrayList<T>();

我想得到T.的.class我怎么能这样做?

I want to get the .class of T. How can I do that?

我的意思是:

myList.getClass()

编辑:
我试过:

I tried that:

 Field genericField = Wrapper.class.getDeclaredField("myList");
 ParameterizedType genericType = (ParameterizedType) genericField.getGenericType();
 Class<?> genericClass = (Class<?>) genericType.getActualTypeArguments()[0];

当我调试它时


genericType

genericType

的值为:


java.util.List

java.util.List

所以我认为这肯定是与该问题不同的问题:获取泛型类型的java.util.List ,因为如果你声明了一个类使用 T 并稍后在另一个方法 T T 指定一些内容c $ c>保持消失。

so I think that this is certainly different issue from that question: Get generic type of java.util.List because of if you declare a class with T and assign something to T later at another method, class that T holds disappear.

推荐答案

你不能因为类型擦除。
泛型类型在运行时是未知的(它被'擦除'),它仅在编译时使用。

You can't because of type erasure. The generic type is not known at runtime (it's 'erased'), it's only used at compile time.

这是java泛型和例如c#generics。

This is a major difference between java generics and c# generics for example.

这篇关于如何获取列表包含的元素类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆