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

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

The signature that the method must have:

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

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

But how can I compare the return type to make sure that only those methods that return Collection<Foo> are selected, and not other collections?

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

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

+6
java reflection
source share
3 answers

There is a method called public Type getGenericReturnType() that can return (if this is the case) ParameterizedType .

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

In particular, using 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 display 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/

+8
source share
+2
source share

Generic type parameters are not saved at runtime (i.e. it is only a compile-time function) in Java, so you cannot do this.

+1
source share

All Articles