zoukankan      html  css  js  c++  java
  • 反射如何判断对象类型并实现强中类型转换

    public static List<Object> readCsvIntoVO(String readPath, Class<?> clazz) {
    List<Object> result = new ArrayList<>();
    Field[] fields = clazz.getDeclaredFields();


    try {
    // 以#分割
    CsvReader csvReader = new CsvReader(readPath,',', Charset.forName("UTF-8"));
    csvReader.readHeaders(); // 跳过表头 如果需要表头的话,不要写这句。
    String[] head = csvReader.getHeaders(); //获取表头
    while (csvReader.readRecord())
    {
    Object record = clazz.newInstance();
    Map<String, String> map = new HashMap<String, String>();
    for (String s : head) {
    String name = s.trim();
    if (name.charAt(0) == 'uFEFF') {
    name = name.substring(1);
    }
    map.put(name,csvReader.get(s));
    System.out.println(s + ":" + csvReader.get(s));
    // String name = s.trim();
    // for (Field field : fields) {
    // field.setAccessible(true);
    //
    // if (name.equals(field.getName())) {
    // Method method = clazz.getMethod("set" + name.substring(0, 1).toUpperCase() + name.substring(1), field.getType());
    // method.invoke(record, StringUtils.get(field.getType(),csvReader.get(s)));
    // break;
    // }
    // }


    // Field f = record.getClass().getDeclaredField(s);
    // f.setAccessible(true);
    // f.set(record, csvReader.get(s));
    }
    BeanUtils.populate(record, map);
    result.add(record);
    }
    csvReader.close();
    } catch (FileNotFoundException e) {
    throw new RuntimeException("文件未找到");
    } catch (IOException e) {
    throw new RuntimeException(e.getMessage());
    } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
    e.printStackTrace();
    }
    return result;
    }
  • 相关阅读:
    bzoj 4361: isn
    bzoj 2560: 串珠子
    bzoj 3622: 已经没有什么好害怕的了
    UOJ #30. 【CF Round #278】Tourists
    Codeforces Round #452 E. New Year and Old Subsequence
    bzoj 2653: middle
    codeforces701C
    codeforces437C
    codeforces518B
    codeforces706C
  • 原文地址:https://www.cnblogs.com/neaos/p/11308220.html
Copyright © 2011-2022 走看看