简体   繁体   English

使用反射在构造函数中创建带参数的对象

[英]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.为清楚起见,省略了try/catch和其他内容。
I can not understand how this works: T instanceObject = constructor.newInstance(new Object[constructor.getParameterTypes().length]);我不明白这是如何工作的: T instanceObject = constructor.newInstance(new Object[constructor.getParameterTypes().length]);
It calls a constructor that has parameters, but passes as arguments Object ?它调用具有参数的构造函数,但作为参数传递Object ?
How does this work?这是如何运作的? Passing Object independent of the actual formal parameters?传递与实际形式参数无关的Object

It attempts to pass dummy parameters which are all null .它尝试传递全为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.我不确定为什么它会跳过零长度构造函数,因为这是您可能无法成功传递任何参数的一个构造函数。

元素数等于构造函数中参数数的对象数组,因此:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM