Proper way to get a generics type argument

社会主义新天地 提交于 2019-12-14 03:07:29

问题


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];

回答1:


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.




回答2:


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> {}


来源:https://stackoverflow.com/questions/8553423/proper-way-to-get-a-generics-type-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!