7

Possible Duplicate:
Java generics constraint require default constructor like C#

I want to set a constraint to type T that it must have a constructor without parameters. In C# it will be like:

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

Is this feature available in Java?

Update: Is there some trick to make generic type T have a constructor?

Community
  • 1
  • 1
franza
  • 2,297
  • 25
  • 39

4 Answers4

5

You cannot define interface for constructors in Java. Nor you cann put any other constraints to type parameters, other than type variance.

ahanin
  • 892
  • 4
  • 8
1

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

ahanin
  • 892
  • 4
  • 8
0

You cannot do this at compile time in Java. I think that the best you can do is to try to verify this at runtime, by 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 invoke this function by doing the following:

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

If this function returns false, then you know the class will have no default constructor, and you can throw an exception or whatever is appropriate for your application.

Jon Newmuis
  • 25,722
  • 2
  • 45
  • 57
0

You could make T extend a class with the constructor you want

public interface Interface<T extends Constructable>{}

public abstract class Constructable{
    public Constructable(params..){
     }
}
Oscar Castiblanco
  • 1,626
  • 14
  • 31
  • But class inheriting Constructable may not have default constructor (without parameters). – ahanin Apr 04 '12 at 15:26
  • of course it has, when inheriting you can not reduce the scope of the access modifier. If the parent class has a public constructor without parameters, then all the subclasses will have this constructor without parameters – Oscar Castiblanco Apr 04 '12 at 15:38
  • 1
    Well, actually, this is not true. It has nothing to do with access modifiers. The set of constructors is unique for each particular class. You have to call one of the super-constructors in every constructor of a child class, unless parent has default constructor. Let's assume B is a sublcass of A. A has a default constructor. If you define only constructor B(String) in B, then you won't be able to instantiate B with just new B(). – ahanin Apr 04 '12 at 15:45
  • You are right, constructors are not inherited. Ups!! – Oscar Castiblanco Apr 04 '12 at 15:53