Reputation: 10419
I need to get all methods in a class that can return a List and then, check for all those method what type of List it is. When I get that type, I need to check if it is an implementation of a particular interface.
I do:
Person person = new Person();
Class c = person.class;
for (Method m: c.getDeclaredMethods()) {
// this gets me all the getters
if (m.getParameterTypes().size() == 0) {
Class<?> returnType = m.getReturnType()
if (returnType.equals(java.util.List.class)) {
// Can get here
// But how to get the class that is used to parameterise the
// list.
}
}
}
How do I get the Class that is used to parameterise a List?
Upvotes: 0
Views: 44
Reputation: 140318
Instead of m.getReturnType()
, use m.getGenericReturnType()
.
This gives you back a Type
. You then need to test if this is an instance of ParameterizedType
: if it is, cast, and extract the type parameters using getActualTypeArguments()
.
Upvotes: 1