[英]How can I create a new instance of a generic class
I create a function like this 我创建一个这样的功能
public <T extends ClientCoporate> void myFunction(List<T> clients){
T client = new T(); // issue
....
}
IDE error Cannot instantiate the type T
IDE错误
Cannot instantiate the type T
Simple question, how can I create a new instance of whatever class extends ClientCoporate
here? 一个简单的问题,如何在这里扩展
ClientCoporate
的任何类的新实例? I try to search but no hope, if you can find any duplicate question feel free to put a flag for me. 我尝试搜索,但没有希望,如果您能找到任何重复的问题,请随时为我标记。 Thanks.
谢谢。
You can't. 你不能
Because generics are erased in run-time and compiler does not know what type of object to create. 因为泛型在运行时被擦除,并且编译器不知道要创建哪种类型的对象。
T
is simply a placeholder, so It is illegal to attempt to instantiate it. T
只是一个占位符,因此尝试实例化它是非法的。
Usually this problem is solved by 通常这个问题可以通过解决
public <T extends ClientCoporate> void myFunction(Class<T> clazz, List<T> clients){
T client = clazz.getDeclaredConstructor().newInstance(); ....
}
One of the reasons you can't do this - though there are probably at least a couple more - is because the concrete type of T is not known at the point you are trying to construct it. 您不能执行此操作的原因之一-尽管可能至少还有几个原因-是因为在您试图构造T的那一刻,T的具体类型尚不明确。 We cannot say for sure that the concrete type of T has a no-argument constructor.
我们不能肯定地说T的具体类型具有无参数构造函数。 The only thing we do know is that is has the methods in
ClientCoporate
. 我们唯一知道的是在
ClientCoporate
有方法。
Consider the following class: 考虑以下类别:
class MyClientCoporate extends ClientCoporate // or implements, it doesn't matter
{
private MyClientCoporate() {}
}
We couldn't use new T()
on this class because the constructor is not public. 我们不能在此类上使用
new T()
,因为构造函数不是公共的。 That's one reason for the compiler to disallow it. 这是编译器不允许这样做的原因之一。
If you can change the signature of the method then I'd do something like this: 如果您可以更改方法的签名,则可以执行以下操作:
public <T extends ClientCoporate> void myFunction(List<T> clients, Supplier<T> constructor){
T client = constructor.get();
...
}
Sample usage: 用法示例:
myFunction(aList, SomeClientCoporateClass::new);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.