2016-05-14 2 views
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()); 
    } 
} 
+1

なぜあなたはそれを試してみませんか?あるいは、それを単体の例にしてコンパイルしてください。 'Collectors.toCollection()'は 'Supplier'引数、BTWを期待しています。 – stholzm

+0

私は試みましたが、コンパイラは特定のタイプのコレクタCollectors.toSet()およびCollectors.toList()にエラーを与えています –

答えて

4

私はあなたのアプローチでタイプセーフな解決策があるとは思わない - あなたは代わりClass、wouldn」を渡す...私は推測する、U

を返されたコレクションを唱えられますCollectors#toCollectionの場合はSupplierを渡すと簡単でしょうか?

public <U extends Collection<T>> U saveOrUpdate(Iterable<T> entities, Supplier<U> supplier) { 
    Iterable<T> savedEntities = this.repository.save(entities); 
    return StreamSupport.stream(savedEntities.spliterator(), false) 
         .collect(Collectors.toCollection(supplier)); 
} 

その後、あなたは結果の型を完全に制御する必要があるだろう、例えば:

saveOrUpdate(entities, HashSet::new); // constructor as Supplier 

そして、それは偶数チェックを入力します。

+0

ありがとうございました、あなたは人生の救世主です。 –

関連する問題