我需要在运行时使用泛型将json字符串解组为Class。类似的东西:
String classname = "this.is.a.class.name.read.at.runtime";
Class cls = Class.forName(classname);
mapper.readValue(jsonPayload, new TypeReference<GenericClass<cls>>() {});
显然,上述方法不起作用,我无法找到一个好的解决方案。
答案 0 :(得分:0)
以下代码解决了我的问题:
String genericParameterClassName = "this.is.a.class.name.read.at.runtime";
Class clazz = Class.forName(genericParameterClassName);
JavaType = mapper.getTypeFactory().constructParametrizedType(GenericClass.class,GenericClass.class,clazz);
GenericClass m = mapper.readValue(jsonPayload, type);