Reputation: 959
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
Reputation: 58888
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