I’ve got a class somewhat like this:
public class Test {
private final List<ISomeType> things = new LinkedList<ISomeType>();
public <T extends ISomeType> Test(Class<T> clazz, int order) {
for (int i = 0; i < order; i++) {
try {
this.things.add(clazz.newInstance());
} catch (Exception e) {
// stackoverflowers use your imagination
}
}
}
}
Where I expect and hope the Class clazz has an accessible no-argument constructor. Is there any way I can enforce presence of it at compile time?
There is no way to enforce constructor requirements at compile time. At runtime you can check class.getConstructors() and ensure there is one that has no args (or just catch the exception like you are in the sample code).
Usually the no-arg constructor requirement is just listed in the Javadoc of the base class or interface.