0

According to the question, Create instance of generic type in Java?

At the time of writing ,the best answer is found to be...

private static class SomeContainer<E> { 
    E createContents(Class<E> clazz) { 
       return clazz.newInstance(); 
    }
 }

But the answer works only for this SomeContainer.createContents("hello");

My condition is to put the class as an inner class in a generic class,then the code should be like this.

SomeContainer<T>.createContents(T);

That will produce compile time error. There is not any created references for T,also. Is there any way to create completly new T object inside the generic class?

Thanks in advance

4

1 回答 1

1

由于在 Java 中实现了泛型,您必须传递Class<T>对象以供进一步使用。

这是示例:

public class Outer<E> {

    private static class Inner<E> {
        E createContents(Class<E> clazz) {
            try {
                return clazz.newInstance();
            } catch (InstantiationException | IllegalAccessException e) {
                return null;
            }
        }
    }  

    private Class<E> clazz;
    private Inner<E> inner;

    public Outer(Class<E> clazz) {
        this.clazz = clazz;
        this.inner = new Inner<>();
    }


    public void doSomething() {
        E object = inner.createContents(clazz);
        System.out.println(object);
    }

}

您也可以使用<? extends E>@gparyani在这里提出的

于 2014-03-12T12:23:44.337 回答