嗯,我想從CSV文件中導入一個字段的名稱,然后將文件名后面的所有數據添加到相應的ArrayList中。我知道如何詢問該類該字段是否存在以及是否存在,但我不知道如何應用該字段的名稱并使用 .add 將元素添加到數組中,請幫助它我的學校項目。try { scanner = new Scanner(new FileInputStream(filename), "UTF-8"); while (scanner.hasNextLine()) { String line = scanner.nextLine(); String[] splitLines = line.split(","); Field field = Main.class.getField("splitLines[0]"); if(ArrayList.class.isAssignableFrom(field.getType())){ for (int i = 0; i < splitLines.length; i++) { /*this is where I want to add all of the Data to the corresponding array*/ } } } scanner.close(); } catch (FileNotFoundException | NoSuchFieldException e) { System.out.println("File not found " + filename); }我希望可以使用 CSV 文件的第一個單詞并將其轉換為類中數組的名稱,然后將 CSV 文件的所有元素添加到數組中。
1 回答

FFIVE
TA貢獻1797條經驗 獲得超6個贊
反射通常不是一個好的解決方案。也許使用 Map 而不是命名數組。
var dataByName = new HashMap<String, List<String>>();
然后,在您從文件中讀取并分割一行后。
var dataList = new ArrayList<String>();
for (int s = 1; s < splitLines.length; s++) {
dataList.add(splitLines[s]);
}
dataByName.put(splitLines[0], dataList);
添加回答
舉報
0/150
提交
取消