The following code receives a class of parameters of the first type, declared in general form in the interface SomeGenericInterface, which is specifically implemented in the class SomeClass.
This code really works.
Question: does it work anyway, i.e. The following two class methods:
getInterfaces()getGenericInterfaces()
Is it guaranteed that there will always be the same number of elements with the same order of interfaces returned by these methods?
Or is there a safer way to do this?
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];
source
share