返回的HashMap
的一個HashMap填充[第一場 - 在一個對象>等領域。
爲了簡單起見,假設有兩個文件:
文件1包含兩個字段(字段1和字段2)。
文件2包含三個字段(f1,f2和f3)。
所以我定義了兩個班,其目的是要在HashMap中值:
Class1{
String field1 = "";
String field2 = "";
}
Class2{
String f1 = "";
String f2 = "";
String f3 = "";
}
現在,我有以下方法:
public static HashMap<String, Class1> readTSV1(String fileName, Class1 c){
...
}
public static HashMap<String, Class2> readTSV2(String fileName, Class2 c){
...
}
...
但我不想定義從不同的文件讀取各種方法:
我想要這樣的:
public static HashMap<String, Object> readTSV(String fileName, Class<?> c){
HashMap<String, c.getClass()> hm = new HashMap<String, c.getClass()>(); //error.
//Look which field names are in type c,
//and then read two or three fields from file,
//and put them as key and values of hm (first field is key, other fields are put in instance of the respective class, and put as values)
return hm;
}
static void main(String[] args){
Class1 c1;
HashMap<String, Class1> hm1 = new HashMap<String, Class1>();
hm1 = readTSV("firstFile.tsv", c1.getClass())
Class2 c2;
HashMap<String, Class2> hm1 = new HashMap<String, Class2>();
hm1 = readTSV("firstFile.tsv", c2.getClass())
...
}
任何想法? ...
聽起來像你真正想讓你的方法返回的是一個'HashMap>'。您可以將'int'傳遞給'readTSV'方法來說明要讀取多少個字段。或者,您可以繼續閱讀字段並將其添加到行末。 –
2014-09-18 19:39:14
它可以工作,但如果適用,這個可讀性更高。 例如,在main中,我們可以說:(Class1)hm1.get(「field1」).field1而不是fields [i]。文件數量及其不同字段太多,可能會導致錯誤。 – Alisa 2014-09-18 19:41:14
那麼,爲了完成你所描述的內容,你需要思考,看看你班上的領域。相信我,添加反射代碼後,它的可讀性會降低很多。 – 2014-09-18 19:42:35