开发者

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 re开发者_如何学Cturn 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/


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜