Checking if the return of a method is List<String> with reflection

User12322341232142 :

I'm trying to get the return type of a method using reflection, however I don't seem to be able to check for List<String> specifically.
I did it in a very hacky way:

if (method.getGenericReturnType().getTypeName().equalsIgnoreCase("java.util.List<java.lang.String>"))

Which isn't really what I should be doing, so I was wondering if there is a better solution.

GotoFinal :

method.getGenericReturnType() returns java.lang.reflect.Type and as you can see in javadocs it have a list of known subtypes:

All Known Subinterfaces:
GenericArrayType, ParameterizedType, TypeVariable<D>, WildcardType

So you can use that to perform few instanceof checks:

// is it ParameterizedType - so any type like Type<GenericType, OrMoreTypes>
if (!(method.getGenericReturnType() instanceof ParameterizedType)) return false;
ParameterizedType parametrizedReturnType = (ParameterizedType) method.getGenericReturnType();
// raw type is just a class without generic part
if (parametrizedReturnType.getRawType() != List.class) return false;
if (parametrizedReturnType.getActualTypeArguments().length != 1) return false;
Type firstArg = parametrizedReturnType.getActualTypeArguments()[0];
return firstArg == String.class;

Note that type might be more complicated, yet still compatible with List if you just want to read some data, like method might have signature like ArrayList<? extends String> and then the check will return false. If you want also support such cases its best to use some libraries, like org.apache.commons.lang3.reflect.TypeUtils.isAssignable as such libraries allow you to create instance of Type definition (these libraries just have own implementations of these interfaces) and perform more advanced checks like isAssignable or isInstance, as sadly java does not provide such API.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=357163&siteId=1