如何从csv文件生成java类

aur*_*ius 3 java csv

我有多个包含大约200到300列的csv文件,我需要使用一对一的映射创建pojos(列也是java类字段).别担心不推荐的事实.如果您知道某个工具或如何自动执行此操作,请投入.

所以你有一个csv文件,包含数千个包含数百列的行,第一行包含列的标题.所以我需要的是,基于第一行(列的标题)来创建一个包含这些标题作为类字段的java类.别介意实际数据.我只需要一个包含这些字段的java类

关于这个帖子有一个问题,但大约在3年前被问过,所以我想已经过时了.

Bin*_*man 6

您可以使用Javassist在运行时生成类:

码:

public static void main(String[] args) throws Exception {
    String[] fieldNames = null;
    Class<?> rowObjectClass = null;
    try(BufferedReader stream = new BufferedReader(new InputStreamReader(Program.class.getResourceAsStream("file.csv")))) {
        while(true) {
            String line = stream.readLine();
            if(line == null) {
                break;
            }
            if(line.isEmpty() || line.startsWith("#")) {
                continue;
            }
            if(rowObjectClass == null) {
                fieldNames = line.split(",");
                rowObjectClass = buildCSVClass(fieldNames);
            } else {
                String[] values = line.split(",");
                Object rowObject = rowObjectClass.newInstance();
                for (int i = 0; i < fieldNames.length; i++) {
                    Field f = rowObjectClass.getDeclaredField(fieldNames[i]);
                    f.setAccessible(true);
                    f.set(rowObject, values[i]);

                }
                System.out.println(reflectToString(rowObject));
            }
        }
    }
}

private static int counter = 0;
public static Class<?> buildCSVClass(String[] fieldNames) throws CannotCompileException, NotFoundException {
    ClassPool pool = ClassPool.getDefault();
    CtClass result = pool.makeClass("CSV_CLASS$" + (counter++));
    ClassFile classFile = result.getClassFile();
    ConstPool constPool = classFile.getConstPool();
    classFile.setSuperclass(Object.class.getName());
    for (String fieldName : fieldNames) {
        CtField field = new CtField(ClassPool.getDefault().get(String.class.getName()), fieldName, result);
        result.addField(field);
    }
    classFile.setVersionToJava5();
    return result.toClass();
}

public static String reflectToString(Object value) throws IllegalAccessException {
    StringBuilder result = new StringBuilder(value.getClass().getName());
    result.append("@").append(System.identityHashCode(value)).append(" {");
    for (Field f : value.getClass().getDeclaredFields()) {
        f.setAccessible(true);
        result.append("\n\t").append(f.getName()).append(" = ").append(f.get(value)).append(", ");
    }
    result.delete(result.length()-2, result.length());
    return result.append("\n}").toString();
}
Run Code Online (Sandbox Code Playgroud)


资源:

file.csv(classpath):

############
foo,bar
############
hello,world
cafe,babe
Run Code Online (Sandbox Code Playgroud)


输出:

CSV_CLASS$0@1324706137 {
    foo = hello, 
    bar = world
}
CSV_CLASS$0@1373076110 {
    foo = cafe, 
    bar = babe
}
Run Code Online (Sandbox Code Playgroud)

  • 我也这样做......我现在可以停下来x) (2认同)