从技术上讲,你CAN使用instanceof
检查对象是否是某种类型。
然而,这是不是一个好主意。
你声明你的方法的方式,它可以接受任何类型的列表,所以它并不一定会是A或B.
很难告诉你要怎么做,但你可能应该让你的方法是通用的。
你可以这样做是这样的:
public static <T> String method(List<T> 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.
}
这里有一个更好的例子:
如果你想创建一个返回列表的第一个元素的一般方法,你会这样做:
public static <T> T firstElement(List<T> theList) {
if (theList == null) {
return null;
}
T objectOfTypeT = theList.get(0);
return objectOfTypeT;
}
请注意,返回现在类型为T
。
因为我们使这个方法是通用的,它可以返回列表中使用的相同类型。
您通常只会返回theList.get(0)
,但我添加了一行以使泛型的用途更加明显。
语法的说明:
这允许编译器说:“这种方法需要类型T的东西哦,看...这样的例子也是T类型如果有人通过字符串列表这种方法,且T必须是一个字符串。如果有人通过整数这种方法的列表,T必须是整数。“
相反,你的方法可以只返回一个字符串,它根本不知道是什么类型的使用列表。
也...
如果A和B都延长了同一个班级,一个名为TheParentClass,你可以声明你的方法是这样的:
public static String method(List<? extends TheParentClass> arg)
这样一来,你就知道多一点关于你的参数的可能类型(并且可以从编译时类型检查中受益)。
声明参数类型为'>'意思是说你对实际类型不感兴趣。 – biziclop 2012-04-13 22:33:35
重复这个http://stackoverflow.com/questions/1942644/get-generic-type-of-java-util-list – evanwong 2012-04-13 22:34:55
@evanwong - 不知道我是否会同意它的愚蠢。 – djangofan 2012-04-13 22:37:32