简体   繁体   English

在泛型类中用Java创建泛型类型的实例

[英]Create instance of generic type in Java within the generic class

According to the question, Create instance of generic type in Java? 根据问题, 在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"); 但是答案仅适用于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. 也没有为T创建任何引用。 Is there any way to create completly new T object inside the generic class? 有什么方法可以在泛型类中创建完全新的T对象?

Thanks in advance 提前致谢

Due to implementation of generics in Java you must pass the Class<T> object for the further use. 由于在Java中实现了泛型,因此必须传递Class<T>对象以供进一步使用。

Here is the example: 这是示例:

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);
    }

}

Also you can use <? extends E> 您也可以使用<? extends E> <? extends E> , proposed by @gparyani here <? extends E> ,由@gparyani 在这里提出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM