How to create a class by name defined in the type field of a generic class
•
Java
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
二维码
