Jim
Jim

Reputation: 19552

Using reflection to create object with parameters in constructor

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?

Upvotes: 1

Views: 603

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533472

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.

Upvotes: 1

Boris Pavlović
Boris Pavlović

Reputation: 64622

An array of objects with number of elements equal to number of parameters in the constructor, hence:

new Object[constructor.getParameterTypes().length])

Upvotes: 1

Related Questions