我有兩個類,classB和classC,都擴展了classLetters。在classB和classC調用的獨立類中,有兩個方法:getBType()和getCType()。兩者中的代碼差不多是重複的,因爲它們都做同樣的事情,除了抓取B類型和抓取C類型。有沒有辦法將這兩個方法合併爲一個名爲getType(String className)的方法,例如,它可以檢測哪個類正在調用它,並根據調用該方法的人來獲取正確類型?這樣我就可以從classB或classC中調用getType(String className),而不必從classB中調用getBType(),並從classC中調用getCType()。這很重要,因爲我將添加更多的類,這將擴展此類,並且我想減少重複代碼的數量。如何使用泛型在Java中創建通用方法?
Collection<classB> bstuff = new Collection<classB>();
Collection<classC> cstuff = new Collection<classC>();
public Collection<classB> getBType() {
ArrayList<classB> b = new ArrayList<classb>(); //this can just return bstuff instead
b.addAll(bstuff); //but i would like to leave this here for the example
return b;
}
public Collection<classC> getCType() {
ArrayList<classC> c = new ArrayList<classc>(); //this can just return cstuff instead
c.addAll(cstuff); //but i would like to leave this here for the example
return c;
}
我想到的是這樣的:請持有按其類索引的集合的數據結構:
static HashMap<String, Collection<? extends classLetters>> allLetters = new HashMa..... etc(); //just an example
//then here i would statically add each class type to the hashmap
public Collection<? extends classLetters> getType(className) {
if (className == "classB") {
ArrayList<classB> b = new ArrayList<classb>();
b.addAll(bstuff);
return b;
}
else if (className == "classC") {
ArrayList<classC> c = new ArrayList<classc>();
c.addAll(cstuff);
return c;
}
}
這仍然具有內自身複製代碼雖然。使用泛型是否可以使用?
public <T> Collection<T> getType() {
ArrayList<T> anyLetter = new ArrayList<T>;
anyLetter.addAll(/* somehow distingush which letter class to put here */);
return anyLetter;
}
「可以檢測其類稱其爲」 < - AFAIK你不能做到這一點 – fge
念念不忘的類層次結構,退後一步,告訴我們什麼是你想完成的任務。 – Piovezan
只需將您的值存儲在'Map,Collection >' –
jmruc