简体   繁体   中英

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.

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/

通用类型参数在Java中不会保留(即,它只是一个编译时功能),因此您无法执行此操作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM