lf215
lf215

Reputation: 959

java: enforce no arg constructor in subclass at run time

I know there's no way to enforce this at compile time, but I was hoping there'd be a way to do this at runtime maybe using reflection.

Upvotes: 1

Views: 170

Answers (1)

You could do it the obvious way, with reflection:

public class Superclass {
    public Superclass() {
        try {
            // get the constructor with no arguments
            this.getClass().getConstructor();
        } catch(ReflectiveOperationException e) {
            throw new RuntimeException("Subclass doesn't have a no-argument constructor, or the constructor is not accessible", e);
        }
    }
}

(Note that getConstructor will only return the constructor if it is public; to allow private constructors too, use getDeclaredConstructor).

Upvotes: 2

Related Questions