How can I create a new instance of a generic class

  • A+
Category:Languages

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

Simple question, how can I create a new instance of whatever class extends ClientCoporate here? I try to search but no hope, if you can find any duplicate question feel free to put a flag for me. Thanks.

 


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. We cannot say for sure that the concrete type of T has a no-argument constructor. The only thing we do know is that is has the methods in 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. 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); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: