Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check that a method returns Collection<Foo> in Java?

I wish to a check if a method exists in an interface based on its signatures.

The signature that the method should have is:

Collection<Foo> methodName(Spam arg0, Eggs arg1, ...)

I can find the methods via Class.getMethods() then find the name, parameters and return type respectively with method.getName(), method.getParameterTypes() and method.getReturnType().

But what do I compare the return type to in order to ensure that only methods that return Collection<Foo> are chosen, and not other collections?

method.getReturnType().equals(Collection.class) 

Since the above will be true for all methods that return a collection, not just for those that return a Foo Collection.

like image 816
brice Avatar asked Aug 20 '10 14:08

brice


2 Answers

There is a method named public Type getGenericReturnType() which can return (if it's the case) a ParameterizedType.

A ParameterizedType can give you more informations on a generic type such as Collection<Foo>.

In particular with the getActualTypeArguments() method you can get the actual type for each parameter.

Here, ParameterizedType represents Collection and getActualTypeArguments() represents an array containing Foo

You can try this to list the parameters of your generic type :

Type returnType = method.getGenericReturnType();
if (returnType instanceof ParameterizedType) {
    ParameterizedType type = (ParameterizedType) returnType;
    Type[] typeArguments = type.getActualTypeArguments();
    for (Type typeArgument : typeArguments) {
        Class typeArgClass = (Class) typeArgument;
        System.out.println("typeArgClass = " + typeArgClass);
    }
}

Sources : http://tutorials.jenkov.com/

like image 181
Colin Hebert Avatar answered Sep 17 '22 23:09

Colin Hebert


See http://download.oracle.com/javase/tutorial/reflect/member/methodType.html

like image 33
Jon Freedman Avatar answered Sep 21 '22 23:09

Jon Freedman