我正在使用 univocity 将一些文件解析为 javabean。这些 Bean 是已编译的类。但是,我希望在运行时生成这些类,然后将文件解析为运行时生成的类。
完整代码在这里:gist
使用 Univocity 库的代码片段:
private static void parseBean(final Class<?> dynamicClass) throws FileNotFoundException {
@SuppressWarnings("unchecked")
final BeanListProcessor<?> rowProcessor = new BeanListProcessor<Class<?>>((Class<Class<?>>) dynamicClass);
final CsvParserSettings parserSettings = new CsvParserSettings();
parserSettings.setProcessor(rowProcessor);
parserSettings.setHeaderExtractionEnabled(false);
parserSettings.getFormat().setDelimiter('|');
parserSettings.setEmptyValue("");
parserSettings.setNullValue("");
final CsvParser parser = new CsvParser(parserSettings);
parser.parse(new FileReader("src/main/resources/person.csv"));
final List<?> beans = rowProcessor.getBeans();
for (final Object domain : beans) {
final Domain domainImpl = (Domain) domain;
System.out.println("Person id is: " + domainImpl.getIdentifier());
System.out.println("Person name is: " + domainImpl.getColumnByIndex(1));
System.out.println();
}
}
该文件如下所示:
0|Eric
1|Maria
所有值似乎都是 null,因此解析文件并将其映射到 bean 时出现问题...
Person id is: null
Person name is: null
是否可以使用 Univocity 库将文件解析为运行时生成的 bean/类?
最佳答案
这里的问题是您的代码没有正确生成 @Parsed
注释。检查一下:
Object o = dynamicClass.newInstance();
Field f = dynamicClass.getDeclaredField("id");
f.setAccessible(true);
java.lang.annotation.Annotation[] annotations = f.getAnnotations();
System.out.println(Arrays.toString(annotations));
您将得到一个空的注释数组。我已经修复了您的代码以正确生成注释:
将您的 addAnnotation
方法更改为:
private static void addAnnotation(final CtClass clazz, final String fieldName, final String annotationName, String member, int memberValue) throws Exception {
final ClassFile cfile = clazz.getClassFile();
final ConstPool cpool = cfile.getConstPool();
final CtField cfield = clazz.getField(fieldName);
final AnnotationsAttribute attr = new AnnotationsAttribute(cpool, AnnotationsAttribute.visibleTag);
final Annotation annot = new Annotation(annotationName, cpool);
annot.addMemberValue(member, new IntegerMemberValue(cpool, memberValue));
attr.addAnnotation(annot);
cfield.getFieldInfo().addAttribute(attr);
}
并这样调用它:
addAnnotation(cc, "id", "com.univocity.parsers.annotations.Parsed","index", 0);
通过此更改,我可以解析如下示例输入:
parser.parse(new StringReader("0|John|12-04-1986"));
并会得到以下输出:
Person id is: 0
Person name is: John
希望这有帮助。
关于java - Univocity - 是否可以将文件解析为运行时生成的 bean/类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39817866/