在Java中获取List中的泛型类型的类型 [英] Get type of generic type inside a List in Java

查看:340
本文介绍了在Java中获取List中的泛型类型的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下功能:

I have the below function:


    public <T> void putList(String key, List<T> lst){
          if (T instanceof String) {
          // Do something       
          }
          if (T instanceof Integer) {
          // Do something   
          }
    }

在这个函数里面,我想要知道< T>是字符串还是整型,所以我想知道是否有办法发现它的类型?我使用了上面的代码,但它产生了错误。

Inside this function, i want to know if <T> is String or Integer so i wonder if there is a way to discover its type? I used the above code but it generated error

预先感谢您。

Thank you in advance.

推荐答案

当类型信息被删除时,找不到 T 的类型。有关更多详细信息,请查看。但是如果列表不是空的,你可以从列表中获得一个元素,并且可以使用 instanceof if else

You can not find the type of T as the type information is erased. Check this for more details. But if the list is not empty, you can get an element from the list and can find out using instanceof and if else

这篇关于在Java中获取List中的泛型类型的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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