views:

55

answers:

2

I have specified an interface (though I can change it to an abstract class if that helps), say T. The users of my API will pass me a Class<? extends T> on which I will call newInstance() (I cannot change that part). How can I ensure that classes that extend T have a constructor which takes no parameter?

+1  A: 

You cannot do this in Java. Since constructors are not inherited, there is no way to force a zero arg constructor to be present unless there are no constructors in the subclass. If that is the case than the object will get a zero arg constructor by default. You can utilize the super keyword to invoke the parent's constructor

Woot4Moo
+2  A: 

You can't force any constructor signatures in Java.

You'd better detect the problem at runtime and throw/propagate a RuntimeException. That's what the serialization mechanism does, for example.

To go a little further - if possible, drop the reliance on .newInstance() and make an annotation @FactoryMethod and use it on a static method that would be a factory method:

public class Foo {

    @FactoryMethod
    public static Foo createFoo() {
       return new Foo();; // or use another constructor, if there is no default?
    }
    ...
}
Bozho