开发者

How to inspect "multi-object" return type

Is there a common reflection approach to find out whether java method returns a set of objects like array, list, set, collection and other iterable subinterfaces? The story behind is that I need to inspect third-party method's return type and say two things:

For example if method's return type is Vector<A>, A[], Set<A>, etc, I want that A to be returned by my code. I'm new to reflection/generics, don't want to re-invent the wheel and not sure my approach is correct. Here's what I've done so far:

  private boolean isMultiple(Class clazz) {
    return clazz.isArray() || Iterable.class.isAssignableFrom(clazz);
  }

  private Class getReturnComponentType(Method m) {
    Class clazz = m.getReturnType();
    if(!isMultiple(clazz)) return clazz; // Not a collection
    // Collection
    if(clazz.isArray()) {
      // How do I get Array's component type?
      // return null;
    } else {
      // How do I get Iterable component type?
      // return null;
    }
  }

Please help.


  1. To get Iterable component type: Besides getReturnType() also use getGenericReturnType() to get generic types. Then compare it to Type subinterfaces: GenericArrayType, ParameterizedType.

  2. To get Array component type use clazz.getComponentType().

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜