Java中基于泛型类型的转换

时间:2019-12-10 21:35:17

标签: java dynamic casting jackson

我想知道是否有可能基于泛型类型转换对象。例如,假设我有一个List<List<List<String>>>对象,并且我想在运行时通过反射将其动态转换为List<List<List<Integer>>>

伪代码目前看起来像:

Class Foo {
   private Long id;
   private Long age;
   private List<List<List<Integer>>> bar;
}


Foo foo = Foo.builder()
     .id(1L)
     .age(1L)
     .bar(someList).build;
Object obj = [[['1', '2', '3'], ['1', '2', '3']]];
for (Field field : foo.getClass().getDeclaredFields()) {

     if (field.getType().isAssignableFrom(List.class) {
         ParameterizedType type = field.getGenericType() //This will be List<List<List<Integer>>>
    //How do I go about converting obj into the same type above, which is that of the field bar in the Foo class

     }



}

我研究了Jackson的ObjectMapper;但是,似乎我必须将TypeFactory函数的类传递给适当的JavaType。

有人有什么建议吗?

0 个答案:

没有答案
相关问题