In C#, I can put a type constraint on a generic parameter that requires the generic type to have a default parameterless constructor. Can I do the same in Java?
In
Java does not do structural typing, so you cannot constrain T
to have a particular constructor or static
method. Only subtyping and supertyping restrictions are permitted.
So, pass an appropriate abstract factory. Use of reflection here, or in virtually any case, is highly inappropriate. There is now a now a suitable generic JDK type for this in the form of java.util.function.Supplier
.
public static T someMethodThatDoesSomeStuff(
Supplier factory
) {
Invoke as:
Donkey donkey = someMethodThatDoesSomeStuff(BigDonkey::new);
(The method reference needn't be a constructor.)