正确的方法来获得泛型类型参数 [英] Proper way to get a generics type argument

查看:115
本文介绍了正确的方法来获得泛型类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码获取在接口 SomeGenericInterface 中一般声明的第一个类型参数类,它在类 SomeClass

这段代码实际上可行。



问题是:它在任何情况下都有效,即是以下两个Class方法:


  • getInterfaces()


  • $ b $ get $ GenericInterfaces()



保证始终有相同数量的元素具有相同的接口顺序这些方法返回?



或者有一些更安全的方法来做到这一点?

 <! -  language:lang-java  - > 

Class clazz = SomeClass.class;

类类[] = clazz.getInterfaces();
类型类型[] = clazz.getGenericInterfaces();
ParameterizedType found = null; $(b)b
$ b(int i = 0;类型[I];
休息;
}
}
if(found == null){
return null;
}
class firstType =(Class)found.getActualTypeArguments()[0];


解决方案

javadoc


如果此对象表示一个类,则返回值是一个数组
,其中包含表示由
类实现的所有接口的对象。数组中的接口对象的顺序对应于
这个对象表示的类的
声明的implements子句中的接口名称的顺序。


blockquote>

所以你的问题的答案是肯定的,相同数量的元素和顺序。


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.

这篇关于正确的方法来获得泛型类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆