我使用univocity将一些文件解析为javabeans。这些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 /类?
答案 0 :(得分:2)
这里的问题是您的代码没有正确生成@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
希望这有帮助。