如何将字段名称应用于 ArrayList,然后向该 ArrayList 添加内容

嗯,我想从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 文件的所有元素添加到数组中。


弑天下
浏览 60回答 1
1回答

FFIVE

反射通常不是一个好的解决方案。也许使用 Map 而不是命名数组。var dataByName = new HashMap<String, List<String>>();然后,在您从文件中读取并分割一行后。var dataList = new ArrayList<String>();for (int s = 1; s < splitLines.length; s++) {&nbsp; &nbsp; dataList.add(splitLines[s]);}dataByName.put(splitLines[0], dataList);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java