You cannot do this at compile time in Java. I think the best thing you can do is try to check this at runtime using reflection to do something like:
public static <T> boolean hasDefaultConstructor(Class<T> cls) { Constructor[] constructors = cls.getConstructors(); for (Constructor constructor : constructors) { if (constructor.getParameterTypes().length == 0) { return true; } } return false; }
Then you can call this function by doing the following:
hasDefaultConstructor(String.class) => true; hasDefaultConstructor(Integer.class) => false;
If this function returns false, then you know that the class will not have a default constructor, and you can throw an exception or something suitable for your application.
source share