有没有一种方法可以获取Java中字段的通用类型?
我有以下对象变量:
protected ScheduleView<WantedClass> scheduleLine1;
protected ScheduleView<SomeOtherClass> scheduleLine2;
现在,我尝试使用反射来获取ScheduleView
具有WantedClass
普通类型的类型的所有对象变量:
Arrays.asList(this.getClass().getDeclaredFields()).stream().map(field -> {
ScheduleView<WantedClass> retValue = null;
System.out.println(field.getGenericType()); // prints control.ScheduleView<dto.WantedClass>
try {
if (field.getType() == ScheduleView.class) { // here I also want to check if the generic type is WantedClass
retValue = (ScheduleView<WantedClass>) field.get(this);
} else {
retValue = null;
}
} catch (IllegalAccessException e) {
retValue = null;
} finally {
return retValue;
}
}).filter(scheduleView -> scheduleView != null).forEach(scheduleView -> {
/* some more code */
});
问题是我还想检查if-Statement的泛型类型是否为WantedClass
。我也尝试使用该方法,getGenericType()
但似乎无法实现以下目的:
field.getGenericType() == ScheduleView<WantedClass>.class
那么,有没有一种方法可以获取字段的通用类型呢?
您必须检查该字段是否为ParameterizedType
,然后检查的内容getActualTypeArguments
,例如
for (Field field : Ideone.class.getDeclaredFields()) {
Type type = field.getGenericType();
if (type instanceof ParameterizedType) {
ParameterizedType ptype = (ParameterizedType) type;
if (ptype.getRawType() == ScheduledView.class) {
if (ptype.getActualTypeArguments().length == 1
&& ptype.getActualTypeArguments()[0] == WantedClass.class) {
// Do whatever with the field.
System.out.println(field.getName());
}
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句