How to create a class by name defined in the type field of a generic class

I want to use Java generics to implement such functions:

public class Test<T> {
    public T data;

    public test() {
        data = new T();
    }
}

However, Java compilation reports errors, such as "type t cannot be instantiated". How can this function be implemented in Java?

Solution

You need classes

public Test(Class<? extends T> klass) {
    data = klass.newInstance();
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>