0

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>

Tal Avissar
  • 10,088
  • 6
  • 45
  • 70

1 Answers1

3

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)
    )
);
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • method.getGenericParameterTypes()[0] is of List – Tal Avissar Oct 24 '21 at 17:25
  • @TalAvissar And your point is...? – Sweeper Oct 24 '21 at 17:27
  • I would like to know if the example you showed above will work also for void foo(String param1, List lst); compared to void fromArrayToCollection(T[] a, Collection c) – Tal Avissar Oct 24 '21 at 18:50
  • It wouldn't work on either of those methods, because they take 2 parameters, but you are calling them with only one parameter using `invoke`. Maybe you have not explained your situation clearly enough, or you do not actually know what you are doing at all... – Sweeper Oct 24 '21 at 18:58
  • @TalAvissar If we remove `String param1` and `T[] a` though, then this will work for the former method, but not the latter, because the latter's parameter type has a type variable, and you can't convert JSON to a type that has type variables in it. But it seems like you have an array here. If you know the `Class` of the array, it is possible to construct a type without type variables, to which you can convert the JSON. – Sweeper Oct 24 '21 at 19:02
  • @TalAvissar If you want to know how to call `fromArrayToCollection` with reflection, that could be asked as another question. – Sweeper Oct 24 '21 at 19:04