Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics constraint require default constructor like C#

Tags:

java

generics

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 C#:

    public static T SomeMethodThatDoesSomeStuff<T>() where T : class, new()
    {
            // ... method body ...
    }

The class and new() constraints mean that T must be a class that can be called with the new operator with zero parameters. What little I know of Java generics, I can use extends to name a required super class. Can I use that (or any other supported operation) to achieve the above functionality?

like image 515
Rich Avatar asked Dec 17 '22 09:12

Rich


2 Answers

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();
like image 67
irreputable Avatar answered Feb 20 '23 03:02

irreputable


No.

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

like image 20
SLaks Avatar answered Feb 20 '23 04:02

SLaks