The correct way to get an argument of type generics

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?

<!-- 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];
0
source share
2 answers

javadoc for both methods:

, , , . , .

"", .

+2

, , . , ( ) ( , ).

class CounterExample<T> implements Interface<T> {}
0

Source: https://habr.com/ru/post/1530601/


All Articles