I can not understand the following code:
Constructor<T>[] constructors = (Constructor<T>[]) clazz.getConstructors();
for(int i = 0; i < constructors.length; i++){
Constructor<T> constructor = constructors[i];
if (constructor.getParameterTypes().length>0){
T instanceObject = constructor.newInstance(new Object[constructor.getParameterTypes().length]);
break;
}
}
Have omitted try/catch and other stuff for clarity.
I can not understand how this works: T instanceObject = constructor.newInstance(new Object[constructor.getParameterTypes().length]);
It calls a constructor that has parameters, but passes as arguments Object?
How does this work? Passing Object independent of the actual formal parameters?
It attempts to pass dummy parameters which are all
null. This can give you an Object but it doesn’t mean it will be a useful one. 😉I am not sure why it skips zero length constructors as this is the one constructor you are likely to be able to pass no arguments successfully.