從技術上講,你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