title: Use an array to call a constructor with varargs
body: <p>Assuming you have a string with the name of a class you want to instantiate and additionally you have an string which contains comma separated the parameters of the constructor. You can assume that the constructor takes only Strings as parameters or varargs of String. You do NOT know before what classes will be used you can only inspect them using reflection.</p>
  
  <p>Example:</p>
  
  <pre><code>String clazzName = "com.example.Sample";
  String parameters = "Apple,Cow,Red"
  
  // can be used to instantiate this class
  
  public class Sample {
      public Sample(String fruit, String animal, String color) { }
  }
  </code></pre>
  
  <p>I wrote an algorithm for doing this using the following logic:</p>
  
  <ol>
  <li>Split the string into an array <code>parameterArray</code> (in the example: <code>parameterArray=["Apple", "Cow", "Red"]</code>)</li>
  <li>Construct an array <code>clazzArray</code> of type <code>Class&lt;?&gt;[]</code> which contains <code>String.class</code> n times where ne is the length of <code>parameterArray</code> (in the example: <code>clazzArray=[String.class, String.class, String.class]</code>)</li>
  <li>Search for a constructor using reflection and invoke it: <code>Class.forName(clazzName).getConstructor(clazzArray).newInstance(parameterArray);</code></li>
  </ol>
  
  <p>This works fine, now assume that you have an class which accepts varargs for one of the parameters:</p>
  
  <pre><code>String clazzName = "com.example.VASample";
  String parameters = "Party Host,Guest 1,Guest2,Guest3"
  
  // can be used to instantiate this class
  
  public class VASample {
      public VASample(String host, String... guests) { }
  }
  </code></pre>
  
  <p>Now <code>parameterArray</code> is an 3 element array and I (of course do not find a constructor). I know that I could get that constructor if I searched for a <code>[String, String[]]</code> constructor on the class. <strong>But how can you know before?</strong></p>
  
  <p>I'm searching for an code-snippet/algorithm/library that finds a constructor for a provided array of parameters paying attention to varargs. So providing it with a <code>[String, String, String]</code> array, it will match either a <code>[String, String, String]</code> constructor, a <code>[String[]]</code> constructor (varargs only) or a <code>[String, String[]]</code> Constructor (arg+varargs).</p>
  
  <p>I know that the java-compile (of course) handles this internally when parsing java source, but how can I emulate something similar using reflection?</p>