如何从csv文件生成java类 [英] How to generate java class from csv file
问题描述
我有多个csv文件包含大约200到300列,我需要创建pojos与一对一的映射(列太java类字段)。不介意不推荐的事实。
如果你知道一个工具或如何自动地执行这项工作。
I have multiple csv files containing about 200 to 300 columns and I need to create pojos out of them with a mapping of one to one (column too java class field). Never mind the fact that is not recommended. If you know a tool or how to do this automatically please pitch in.
所以你有一个csv文件,包含数千行,第一行包含列的标题。所以我需要,基于第一行(列的头)创建一个包含这些头作为类字段的java类。不要介意实际的数据。我只需要一个带有这些字段的java类。
so you have a csv file, containing thousands of rows with hundreds of columns, the first row contains the header of the columns. SO what I need, based on the first row (header of column) to create a java class that contains those headers as class fields. Never mind the actual data. I just need a java class with those fields
这个帖子有一个问题,但是这是在3年前问过的,所以我猜测已经过时了。
There was a question regarding somewhat this post but this was asked about 3 years ago, so I guess is obsolete.
推荐答案
您可以使用Javassist在运行时生成类:
You can use Javassist to generate classes at runtime:
代码:
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();
}
资源:
file.csv(classpath):
file.csv (classpath):
############
foo,bar
############
hello,world
cafe,babe
输出:
CSV_CLASS$0@1324706137 {
foo = hello,
bar = world
}
CSV_CLASS$0@1373076110 {
foo = cafe,
bar = babe
}
这篇关于如何从csv文件生成java类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!