在Java中創建泛型類型的實例?是否可以在Java中創建泛型類型的實例?我的想法是基于我所看到的答案no (由于類型擦除),但如果有人能看到我缺少的東西,我會感興趣的:class SomeContainer<E>{
E createContents()
{
return what???
}}編輯:原來超級代幣可以用來解決我的問題,但它需要大量基于反射的代碼,如下所示。我暫時不談這個問題,看看有沒有人能拿出和伊恩·羅伯遜截然不同的東西Artima條款.
4 回答
慕蓋茨4494581
TA貢獻1850條經驗 獲得超11個贊
public abstract class Foo<E> {
public E instance;
public Foo() throws Exception {
instance = ((Class)((ParameterizedType)this.getClass().
getGenericSuperclass()).getActualTypeArguments()[0]).newInstance();
...
}}// notice that this in anonymous subclass of Fooassert( new Foo<Bar>() {}.instance instanceof Bar );
收到一只叮咚
TA貢獻1821條經驗 獲得超5個贊
interface Factory<E> {
E create();}class SomeContainer<E> {
private final Factory<E> factory;
SomeContainer(Factory<E> factory) {
this.factory = factory;
}
E createContents() {
return factory.create();
}}添加回答
舉報
0/150
提交
取消
