有没有一种方法可以在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语句中检查泛型类型是否为WantedClass
。我也尝试使用getGenericType()
方法,但似乎这样做不可能:
field.getGenericType() == ScheduleView<WantedClass>.class
那么是否有一种方法可以获得字段的通用类型?
System.out.println(field.getGenericType());
会打印出control.ScheduleView<dto.WantedClass>
? - Michael Langhammer