I know Java's generics are somewhat inferior to .Net's.
I have a generic class Foo<T>
, and I really need to instantiate a T
in Foo
using a parameter-less constructor. How can one work around Java's limitation?
I know Java's generics are somewhat inferior to .Net's.
I have a generic class Foo<T>
, and I really need to instantiate a T
in Foo
using a parameter-less constructor. How can one work around Java's limitation?
And this is the Factory implementation, as Jon Skeet suggested:
Output:
From https://stackoverflow.com/a/2434094/848072. You need a default constructor for T class.
Quick solution that worked for me. I see there is already an answer for this and this may not even be the best way to go about it. Also, for my solution you'll need Gson.
However, I ran into a situation where I needed to create an instance of a generic class of type
java.lang.reflect.Type
.The following code will create an instance of the class you want with null instance variables.
Where
myKnownType
is known before hand and obtained viaTypeToken.getType()
.You can now set appropriate properties on this object. Again, this may not be the best way to do this but it works as a quick solution if that's what you need.
For Java 8 ....
There is a good solution at https://stackoverflow.com/a/36315051/2648077 post.
This uses Java 8
Supplier
functional interfaceSimple answer is "you cant do that" java uses type erasure to implment generics which would prevent you from doing this.
One way (there could be others) is to pass the object that you would pass the instance of T to the constructor of
Foo<T>
. Or you could have a methodsetBar(T theInstanceofT);
to get your T instead of instantiating in the class it self.Here's a rather contrived way to do it without explicitly using an constructor argument. You need to extend a parameterized abstract class.