Limitations in the implementation of the interface in java

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

I want to set a restriction on type T so that it has a constructor without parameters. In C #, it will look like this:

public interface Interface<T> where T : new() { }

Is this feature available in Java?

Update: is there any trick to make generic type T a constructor?

+6
source share
4 answers

Answering your updated question: only a class can have a constructor in Java, T is a type literal, it doesn't have to be a class. At runtime using reflection, you can check if your ParameterizedType class has a parameter that is actually a class, and if it has an empty constructor.

+1
source

You cannot define an interface for constructors in Java. You also cannot impose any other restrictions for entering parameters other than type.

+5
source

You cannot do this at compile time in Java. I think the best thing you can do is try to check this at runtime using reflection to do something like:

 public static <T> boolean hasDefaultConstructor(Class<T> cls) { Constructor[] constructors = cls.getConstructors(); for (Constructor constructor : constructors) { if (constructor.getParameterTypes().length == 0) { return true; } } return false; } 

Then you can call this function by doing the following:

 hasDefaultConstructor(String.class) => true; hasDefaultConstructor(Integer.class) => false; 

If this function returns false, then you know that the class will not have a default constructor, and you can throw an exception or something suitable for your application.

0
source

You can make T an extension of the class using the constructor you want

 public interface Interface<T extends Constructable>{} public abstract class Constructable{ public Constructable(params..){ } } 
0
source

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


All Articles