문제

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:

If this object represents a class, the return value is an array containing objects representing all interfaces implemented by the class. The order of the interface objects in the array corresponds to the order of the interface names in the implements clause of the declaration of the class represented by this object.

so the answer to both your questions is yes, the same number of elements and in the same order.

다른 팁

Does it work in any case

No, but not for the reasons you suspect. It will only work if the class implements the interface directly (as opposed to inherting the interface from a super class), and specifies a concrete type for the type parameter (as opposed to using a type parameter, as in the following example).

class CounterExample<T> implements Interface<T> {}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top