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:
- Does method return开发者_开发知识库 set of objects (in human sense)?
- If yes - what is the component type?
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.
To get Iterable component type: Besides
getReturnType()
also usegetGenericReturnType()
to get generic types. Then compare it toType
subinterfaces: GenericArrayType, ParameterizedType.To get Array component type use
clazz.getComponentType()
.
精彩评论