views:

80

answers:

3

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.

+1  A: 

Generic type parameters are not retained at runtime (i.e. it's a compile-time only feature) in Java so you cannot do this.

Raoul Duke
+4  A: 

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/

Colin Hebert
Thanks Colin. That did it and the article explains a little bit more about how and why.
brice
I'm wondering, would [method.getTypeParameters()](http://download.oracle.com/javase/6/docs/api/java/lang/reflect/GenericDeclaration.html) work too?
brice
Method.getTypeParameters() give generic informations on the method itself for example Collections.unmodifiableList :`public static <T> List<T> unmodifiableList(List<? extends T> list) {` The result will be an array containing "T"
Colin Hebert