3
是基于类型的特定集合的泛型类型我想编写一个泛型类,默认情况下返回一个集合但如果调用函数需要特定类型说List或Set,该方法应该能够产生它。在java中可能吗?如果我没有正确地做,请纠正我。返回基于类型传递给参数
public <U extends Collection> U saveOrUpdate(Iterable<T> entities, Class<U> klass) {
Iterable<T> savedEntities = this.repository.save(entities);
Type type = klass.getClass().getGenericSuperclass();
ParameterizedType pt = (ParameterizedType) type;
if (pt.getTypeName().equalsIgnoreCase(Set.class.getName())) {
return StreamSupport.stream(savedEntities.spliterator(), false)
.collect(Collectors.toSet());
} else if (pt.getTypeName().equalsIgnoreCase(List.class.getName())) {
return StreamSupport.stream(savedEntities.spliterator(), false)
.collect(Collectors.toList());
} else {
return StreamSupport.stream(savedEntities.spliterator(), false)
.collect(Collectors.toCollection());
}
}
你为什么不试试呢?或者甚至更好,将它作为一个独立的例子并编译它。 'Collectors.toCollection()'需要一个'Supplier'参数,BTW。 – stholzm
我试过了,但是编译器给出了特定类型的收集器Collectors.toSet()和Collectors.toList() –