GenericTypeResolver.resolveTypeArguments returns n

2019-09-24 16:46发布

问题:

I have the following code:

List strings = new ArrayList<String>();
strings.add("string");
System.out.println(GenericTypeResolver.resolveTypeArguments(String.class, strings.getClass()));

It prints null.

I cannot understand this method signature.

I want to check that strings is parameterized with String.

How do you use resolveTypeArguments properly ?

P.S.

My example just dummy.

P.S.2

I know that spring can do something like this with Convertor interface

回答1:

This utility is made to look up reified type parameters. What that means in this case is that the information must be available in the class itself.

The first parameter is the class you're trying to resolve the types of. The second parameter is the superclass or interface the first class implements, which has generic type parameters.

Here would be one example for Integer (which implements Comparable<Integer>):

Class[] typeParams = GenericTypeResolver.resolveTypeArguments(
                            Integer.class, Comparable.class);
//typeParams would be [Integer.class] 

In your example, the type parameter of strings has not been reified (it has been erased) and so this utility will return null, even if you were to fix how you were calling it (which would be resolveTypeArguments(strings.getClass(), Collection.class))