The following code gets the first type parameter class declared generically in the interface SomeGenericInterface which gets concretely implemented in the class SomeClass.
This code actually works.
The question is: Does it work in any case, i.e. are the following two Class methods:
getInterfaces()getGenericInterfaces()
guaranteed to always have the same number of elements with the same respective order of the interfaces returned by these methods?
Or is there some safer way to do this?
<!-- language: lang-java -->
Class clazz = SomeClass.class;
Class classes[] = clazz.getInterfaces();
Type types[] = clazz.getGenericInterfaces();
ParameterizedType found = null;
for (int i=0; i<classes.length; i++) {
if ( classes[i] == SomeGenericInterface.class) {
found = (ParameterizedType) types[i];
break;
}
}
if (found == null) {
return null;
}
Class firstType = (Class) found.getActualTypeArguments()[0];
The javadoc for both methods states:
so the answer to both your questions is yes, the same number of elements and in the same order.