I need to match method returned type to class. How can I do that?
public class MethodTest {
public static List<String> getStringList()
{
return null;
}
public static void main(String[] args)
{
for(Method method : MethodTest.class.getMethods())
{
Type returnType = method.getGenericReturnType();
// How can for example test if returnType is class List?
}
}
}
I believe you can check for the
Typebeing aParameterizedTypeand use the raw type if so:This will cope with
List<?>andList, but it won’t match methods declared to return a concrete implementation ofList. (UseisAssignableFromfor that.)Note that missingfaktor’s answer is a good one if you’re not going to use anything else about the return type’s generic type arguments etc.