我需要获取JSON
输入 Pojo 实例,并且我正在使用Jackson 2
库,下面readValue
的方法可以使用 typeReference 反序列化:
POJO_ClassName p = mapper.readValue(new TypeReference< POJO_ClassName >() {});
但问题是,由于POJO
在运行时动态创建和加载,我如何获得JSON
实例POJO
/对象,因为我没有上述语句的完全限定类 (POJO_ClassName) 名称?
注意:我使用jsonSchema2pojo
库在运行时生成POJO
类。
这是代码片段,我POJO
用于JSON
在运行时生成并尝试
String classPath="com.EnrichmentService.Thread72";
String classLocation = System.getProperty("user.dir")
+ "/src/main/java"; JCodeModel codeModel = new JCodeModel();
final RuleFactory ruleFactory = new RuleFactory(config,
new Jackson2Annotator(config), new SchemaStore());
final SchemaMapper mapperSchema = new SchemaMapper(ruleFactory,
new SchemaGenerator());
mapperSchema.generate(codeModel, "EsRootDoc",classPath, json);
codeModel.build(new File(classLocation)); // generates pojo classes
// Till above jsonSchema2Pojo pojo generation all Good !!
// EsRootDoc instance is needed for further drools drl validations.
com.EnrichmentService.Thread72.EsRootDoc p = mapper.readValue(new TypeReference<com.EnrichmentService.Thread72.EsRootDoc>() {});
// see alternative way as well in my 24Aug17 edit at the end of this question
但是由于com.EnrichmentService.Thread72.EsRootDoc
尚未生成,编译器会出错到找不到类。
要点:
1) 在运行时迭代生成相同的 Pojo 类,但随着 JSON 输入的每次变化具有不同的属性。
2)甚至尝试过 Object pojo =mapper.readValue(json,Class.forName("com.EnrichmentService.Thread72.EsRootDoc")); 因为 class.forName 不会替换现有的类!
编辑 24 Aug17 - 这是我的自定义类加载器:
注意:Indexer 是在运行时加载动态 EsRootDoc/POJO 类的类。
static class TestClassLoader extends ClassLoader {
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
if (name.equals("com.EnrichmentService.Thread72.EsRootDoc")) {
try {
InputStream is = Indexer.class.getClassLoader().getResourceAsStream("com/EnrichmentService/Thread72/EsRootDoc.class");
byte[] buf = new byte[is.available()];
int len = is.read(buf);
Class<?> c=defineClass(name, buf, 0, len);
resolveClass(c);
return c;
} catch (IOException e) {
throw new ClassNotFoundException("", e);
}
}
return getParent().loadClass(name);
}
}
我曾尝试使用上面的 TestClassLoader 自定义类加载器作为替代方式,如下所示:
Class cls = new TestClassLoader().loadClass("com.EnrichmentService.Thread72.EsRootDoc");
Object obj = cls.newInstance();
cls.getMethod("getCrawlerSource").invoke(obj);
p=mapper.readValue(json, cls); // but here i am getting the same deserialization exception as earlier.
参考了一个旧答案@如何在 java 中替换正在运行的应用程序中的类?
Edit2:24Aug17 面临堆栈跟踪的异常在这里:https ://pastebin.com/ckCu2uWx