You can not. There is no way to “require” a constructor without parameters and force the compiler to use it, and by definition, to create an instance of the class, you must provide it with the necessary parameters or else you will end up working with an object that violates (because it is not initialized properly).
The right way to do this at the code level is with a factory object and interfaces. I assume that you need to use reflection because you do not know about types at compile time; In this case, there should also be a "Factory" that knows how to instantiate each type. This factory must be built / compiled with the type in question so that it knows and can call the corresponding constructor. Then, the factory implements an interface that your code knows, such as "ObjectFactory", which allows you to delegate a factory to create objects. Then you will have some method that the factory object can use to register as being responsible for any types that it can create.
In the code that comes with the classes you are trying to create:
static { FactoryRegistry.register(TypeA.class, new TypeAFactory()); }
And in your code:
Class<?> unknownClass = ...; Object obj = FactoryRegistry.getFactory(unknownClass).newInstance();
(where you have a Factory interface that TypeAFactory implements and points to the newInstance method)
You do not know what unknownClass or how to create it, but if the code that came with this class registered a factory, you can request a factory for this and ask it to create an object for you. If unknownClass really TypeA.class , then the registry will return the TypeAFactory that was registered to create the objects.
Alternatively, you can simply require that the authors of any code loaded by your infrastructure dynamically include a constructor with no arguments. It is not hard applied, but it may be easier for authors.
source share