The Java generics restriction requires a default constructor such as C #

In C #, I can put a type constraint on a generic parameter, which requires a generic type to have a constructor without parameters without parameters. Can I do the same in Java?

In C #:

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

Class restrictions and new () mean that T must be a class that can be called by a new operator with zero parameters. What I know little about Java generics, I can use extends to indicate the required superclass. Can I use this (or any other supported operation) to achieve the above functions?

+3
source share
2 answers

Not; in Java, a typical solution is to pass a class, and doc is a 0-arg constructor requirement. This, of course, is a less static check, but not a big problem.

 /** clazz must have a public default constructor */ public static <T> T f(Class<T> clazz) return clazz.newInstance(); 
+8
source

Not.

Due to type erasure, the type <T> not known at run time, so it cannot be created for it.

+3
source

Source: https://habr.com/ru/post/912406/


All Articles