1

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.

Community
  • 1
  • 1
lf215
  • 1,185
  • 7
  • 41
  • 83
  • 2
    What would that achieve? Your program errors out with a runtime exception? How is that different from what would happen if the constructor was missing and you tried to call it? – Thilo Apr 20 '16 at 00:10
  • If anything, you may want to look at a custom build step (maybe triggered by an annotation) that can verify the class structure (similar to running Findbugs or unit tests during builds). http://stackoverflow.com/a/803433/14955 – Thilo Apr 20 '16 at 00:12
  • There's no question in this question. Presumably you want to ask how to do it? – user253751 Apr 20 '16 at 00:23
  • Why? What do you care innthe base class about how derived classes are constructed? This is not a proper concern of a base class. – user207421 Apr 20 '16 at 00:48

1 Answers1

2

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).

user253751
  • 57,427
  • 7
  • 48
  • 90