Javagenerics类型参数
我有一个方法,它以List
作为参数。
public static String method(List arg){ // Do something based on type of the list } //I call the method as below List listA = new ArrayList(); List listB = new ArrayList(); method(listA); method(listB);
在method
,我如何知道arg
是ClassA
List
还是ClassB
List
?
来自用户称为Romain的回答“如果你使用<?>,你的意思是你不会在任何地方使用参数化类型。要么转到特定类型(在你的情况下似乎是List
此外,我相信,如果你使用问号,编译器不会捕获类型不匹配,直到运行时(已实现;有效Java的第119页),绕过擦除,并有效地消除了使用generics类型带来的好处???
回答提问者的问题:如果你使用List
从技术上讲,您可以使用instanceof
来检查对象是否是某种类型。
但是……那不是个好主意。
你声明方法的方式,它可以接受任何类型的List,所以它不一定是A或B.
很难说你想要做什么,但你可能应该让你的方法通用。
你可以这样做:
public static String method(List arg) { // We now know that the type of the list is T, which is // determined based on the type of list passed to this // method. This would demonstrate the point better if // the return type was T, but I'm leaving the return type // as String, because that's what your code returns. }
这是一个更好的例子 :
如果要创建一个返回列表第一个元素的generics方法,可以这样做:
public static T firstElement(List theList) { if (theList == null) { return null; } T objectOfTypeT = theList.get(0); return objectOfTypeT; }
请注意,返回类型现在为T
因为我们使这个方法通用,所以它可以返回List中使用的相同类型。
您通常只返回theList.get(0)
,但我添加了一行以使generics的目的更加明显。
语法说明:
-
表示此方法采用一个名为T的类型参数。 -
紧接着的
T
是返回类型(就像你通常会返回String,Integer等…)。 -
List参数中的
T
是编译器如何知道T
是什么的。
这允许编译器说:“ 这个方法需要类型为T的东西。看看……列表也是T类型。如果有人将一个字符串列表传递给这个方法,那么T必须是一个字符串。如果有人通过这个方法的整数列表,T必须是一个整数。 “
相反,您的方法只能返回一个String,并且不知道List中使用了什么类型。
也…
如果A和B都扩展了同一个类,名为TheParentClass,你可以像这样声明你的方法:
public static String method(List extends TheParentClass> arg)
这样,您就可以了解更多关于参数的可能类型(并且可以从编译时类型检查中受益)。
举个例子,没有办法知道List
的generics类型参数是什么。 它们在实例级别被擦除。