newbie
newbie

Reputation: 24645

Matching Method return type to class in Java?

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?
        }       
    }

}

Upvotes: 2

Views: 645

Answers (3)

UVM
UVM

Reputation: 9914

I think you can check like this:

if(returnType instanceof List) {

}

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503449

I believe you can check for the Type being a ParameterizedType and use the raw type if so:

if (returnType instanceof ParameterizedType)
{
    System.out.println("Parameterized");
    ParameterizedType parameterized = (ParameterizedType) returnType;
    System.out.println(parameterized.getRawType().equals(List.class));
}
else
{
    System.out.println("Not parameterized");
    System.out.println(returnType.equals(List.class));
}

This will cope with List<?> and List, but it won't match methods declared to return a concrete implementation of List. (Use isAssignableFrom for 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.

Upvotes: 5

missingfaktor
missingfaktor

Reputation: 92106

If you are not interested in List's type parameter, you can just use method.getReturnType().equals(List.class) to test if the method returns a List.

However note that this will return false if the method in question happens to return a subtype of List. (Thanks @cHao for pointing that out!) If you want that case to be taken care of, use List.class.isAssignableFrom(method.getReturnType()) instead.

Upvotes: 3

Related Questions