How can I use TypeUtils.parameterize to represent nested generic type like Result<List<R>>

354 Views Asked by At

I'm using org.apache.commons.lang3.reflect.TypeUtils and jackson library to handle object deserialization。

One layer nested generic type can be handled well with the following code.

            final Result<R> ret = mapper.readValue(reader, new TypeReference<>() {
                @Override
                public java.lang.reflect.Type getType() {
                    return TypeUtils.parameterize(Result.class, req.clazz);
                }
            });

But I'm not sure how to handle generic type like Result<T<R>>.

Can I use TypeUtils.parameterize(Result.class, T, R) to represent Result<T, R> and TypeUtils.parameterize(Result.class, TypeUtils.parameterize(T, R)) to Result<T<R>

1

There are 1 best solutions below

0
rzwitserloot On

Map<String, Integer>:

Type mapOfStringsToIntegers =
  TypeUtils.parameterize(Map.class, String.class, Result.class);

List<List<String>>:

Type listOfStrings = TypeUtils.parameterize(List.class, String.class);
Type listOfListOfStrings = TypeUtils.parameterize(List.class, listOfStrings);

Seems straightforward.

I think you're not using jackson optimally here. Java is highly nominal. You don't want a Map<String, List<List<Integer>>>. You want to create a simple, non-parameterized class that exactly describes the XML or JSON you want to send or receive, and then just supply that. Then jackson will take care of it. If you must, have a field in that class that is e.g. a List<List<String>> - jackson can figure out fields with no effort on your part. No need for apache's TypeUtils.