加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java泛型类型参数

发布时间:2020-12-15 02:56:46 所属栏目:Java 来源:网络整理
导读:我有一个方法,它采用List?作为一个论点. public static String method(List? arg){ // Do something based on type of the list}//I call the method as belowListClassA listA = new ArrayListClassA();ListClassB listB = new ArrayListClassB();method(l
我有一个方法,它采用List<?>作为一个论点.
public static String method(List<?> arg){
     // Do something based on type of the list
}

//I call the method as below
List<ClassA> listA = new ArrayList<ClassA>();
List<ClassB> listB = new ArrayList<ClassB>();
method(listA);
method(listB);

在方法中,我如何知道arg是ClassA的List还是ClassB的List?

解决方法

从用户称为 Romain的答案“如果你使用<?>”,你的意思是你不会在任何地方使用参数化类型.要么转到特定类型(在你的情况下似乎是List< String>)或者到非常通用的List< Object>“

此外,我相信,如果你使用问号,编译器不会捕获类型不匹配,直到运行时(已实现;有效Java的第119页),绕过擦除,并有效地消除了使用泛型类型带来的好处???

回答提问者的问题:如果你使用List<对象>然后尝试将它转换为A或B,可能使用instanceOf,这可能是一种告诉它是什么的方法.我敢打赌,有一个更好的方法来做到这一点.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读