GenericTypeResolver.resolveTypeArguments returns null

非 Y 不嫁゛ 提交于 2019-12-26 14:46:11

问题


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))



来源:https://stackoverflow.com/questions/34271764/generictyperesolver-resolvetypearguments-returns-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!