Java generics constraint require default constructor like C#

后端 未结 3 1031
一向
一向 2020-12-21 05:03

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

相关标签:
3条回答
  • 2020-12-21 05:36

    No; in Java the typical solution is to pass a class, and doc the requirement of 0-arg constructor. This is certainly less static checking, but not too huge a problem

    /** clazz must have a public default constructor */
    public static <T> T f(Class<T> clazz)
        return clazz.newInstance();
    
    0 讨论(0)
  • 2020-12-21 05:39

    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<T>(
        Supplier<T> factory
    ) {
    

    Invoke as:

    Donkey donkey = someMethodThatDoesSomeStuff(BigDonkey::new);

    (The method reference needn't be a constructor.)

    0 讨论(0)
  • 2020-12-21 05:55

    No.

    Because of type erasure, the type of <T> is not known at runtime, so it's inherently impossible to instantiate it.

    0 讨论(0)
提交回复
热议问题