title: instantiate object with array elements as parameters java
body: <p>I am making an IoC Container in java, using reflection, to auto instantiate dependencies. I've got it working, recursively, but the instantiation is clumsy and not very intuitive.</p>
  
  <pre><code>import java.lang.reflect.Constructor;
  import java.util.ArrayList;
  
  public class IoC {
  
      public void register(Object type)
      {
  
      }
  
      public Object resolve(String type) throws Exception {
  
          // Get class
          Class c = Class.forName(type);
  
          // Get class constructors
          Constructor[] constructors = c.getConstructors();
  
          if (constructors.length &gt; 1) {
              throw new Exception(type + " has more than one constructor. Can't auto instantiate!");
          }
  
          // The one constructor
          Constructor constructor = constructors[0];
  
          // Get constructor parameter types
          Class[] parameters = constructor.getParameterTypes();
  
          // ArrayList to hold dependencies
          Object[] dependencies = new Object[parameters.length];
  
          if (parameters.length &gt; 0) {
              // Get dependencies recursively
              for (int i = 0; i &lt; parameters.length; i++) {
                  dependencies[i] = resolve( parameters[i].getName() );
              }
          }
  
          if(dependencies.length &gt; 4)
          {
              throw new Exception("Too many dependencies, consider refactoring!");
          }
          else if(dependencies.length == 1) {
              return constructor.newInstance(dependencies[0]);
          }
          else if(dependencies.length == 2) {
              return constructor.newInstance(dependencies[0], dependencies[1]);
          }
          else if(dependencies.length == 3) {
              return constructor.newInstance(dependencies[0], dependencies[1], dependencies[2]);
          }
          else if(dependencies.length == 4) {
              return constructor.newInstance(dependencies[0], dependencies[1], dependencies[2], dependencies[3]);
          }
  
          return constructor.newInstance();
      }
  
  }
  </code></pre>
  
  <p>As you can see, what i'm doing, is checking the length of the dependencies array, and then passing in the corresponding number of arguments.</p>
  
  <p>So what i'm asking is, is there a way to just pass in the dependencies array when instantiating, and the array elements are automatically passed as separate arguments?</p>
  
  <p>Hope it makes sense :)</p>