以下代码段在Eclipse的倒数第二行中显示警告“类型安全:未经检查的从对象到数组列表的转换”。只是想知道我能做些什么来改善它。该代码用于从xml文件读取对象。
private List<Facility> getFacilityCodes() {
InputStream in = this.getClass().getResourceAsStream("./resources/facility.xml");
String xml = convertStreamToString(in);
XStream xstream = new XStream(new StaxDriver());
xstream.alias("Facility", Facility.class);
xstream.alias("Facilities", List.class);
ArrayList<Facility> facilities = (ArrayList<Facility>) xstream.fromXML(xml);
return facilities;
}
最佳答案
问题在于,只要返回的对象是ArrayList
,强制转换就会成功,但是由于擦除操作,不能保证每个元素都是Facility
。如果愿意,您可以自己做。
ArrayList<Facility> facilities =
((ArrayList<?>) xstream.fromXML(xml)).stream()
.filter(Facility.class::isInstance)
.map(Facility.class::cast)
.collect(Collectors.toCollection(ArrayList::new));