デフォルトでコレクションを返すジェネリッククラスを記述しようとしていますが、呼び出し関数で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()にエラーを与えています –