I want to be able to create Jackson TypeReference with dynamic method parameter type with below example using reflection method.getParameterTypes()1.
Since TypeReference only takes compile type parameters but I read in SO you can do some trick to let it also to work with dynamic types.
Method method = methodsMap.getOrDefault("createXXX".toLowerCase(), null);
if(method != null && myBean!= null){
Object retval = method.invoke(myBean, mapper.convertValue(product , new TypeReference<method.getParameterTypes()[0]>(){}));
}
where method.getParameterTypes()[0] is of type of java util generic list (the type erasure issue)
List<MyPojo>
CodePudding user response:
You should not use getParameterTypes
at all. You should use getGenericParameterTypes
, to get a Type
instead. You can then pass that Type
to a TypeFactory
to get a JavaType
, which convertValue
also accepts.
Type parameterType = method.getGenericParameterTypes()[0];
method.invoke(myBean, mapper.convertValue(
product,
mapper.getTypeFactory().constructType(parameterType)
)
);