Java泛型类型参数 [英] Java generic type arguments

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

问题描述

我有一个以 List <?>< / code>作为参数的方法。

  public static String method(List<> arg){
//根据列表的类型做某事
}

//我打电话方法如下
List< ClassA> listA = new ArrayList< ClassA>();
列表< ClassB> listB = new ArrayList< ClassB>();
方法(listA);
方法(listB);

方法中,我怎么知道if arg ClassA 或$ List $ c> List of ClassB

解决方案

来自罗曼的用户的回答如果您使用< ;?>,则表示您不打算在任何地方都可以使用参数化类型,或者转到特定的类型(在你的情况下,它似乎是List< String>)或者到非常通用的List< Object>的类型。 ,我相信如果你使用问号,那么编译器不会直到运行时才捕获类型不匹配(有效Java的p.119),绕过擦除,并有效地减少使用泛型类型获得的好处???



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


I have a method which takes a List<?> as an argument.

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);

In method, how do I know if arg is a List of ClassA or a List of ClassB?

解决方案

From an answer by the user called Romain " If you use < ?>, you mean you aren't going to use the parametrized type anywhere. Either go to the specific type (in your case it seems List< String>) or to the very generic List< Object> "

Also, I believe that if you use the question mark the compiler wont catch type mismatches until runtime (reified; p.119 of Effective Java), bypassing erasure, and effectively elimating the benefit you get from using generic types???

TO answer the question of the questioner: if you use List< Object> and then try to cast it to A or to B , possibly using instanceOf , that might be a way to tell what it is. I bet there is a better way to do it than that though.

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

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