1

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?

3
  • you need all arguments to be non-primitive and the c-tor to make sense w/ having all parameters null Commented Sep 12, 2012 at 7:51
  • @bestsss:Individual parameters are automatically unwrapped to match primitive formal parameters from Javadoc Commented Sep 12, 2012 at 7:58
  • Jim, except null is unwrapped to NPE. I know the spec and even the impl, really no need to quote. The unwrapping is simple: Integer.intValue(), Double.doubleValue() - hence the NPE. Commented Sep 12, 2012 at 9:05

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

also can lead to NPE if any of the arguments are primitive
it could lead to an NPE even if the arguments are not primitive but expect you to pass it something. ;) I assume the outer loop catches exceptions and keeps trying if it gets one.
I mean it won't even get to the c-tor. Of course, any arbitrary data can lead to errors but at w/ primitives the c-tor won't even be invoked.
1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.