title: Reflection overload. Populating reflected array for reflected varargs method
body: <p>I'm in the middle of a contender for the greatest kludge of all time. I need to use Spring JDBC without ever making reference to it. A custom classloader is providing the context and I need to use reflection to invoke the methods. One such method is <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/jdbc/core/simple/SimpleJdbcCall.html#declareParameters%28org.springframework.jdbc.core.SqlParameter...%29" rel="nofollow">SimpleJdbcCall.declareParameters(SqlParameter ...)</a></p>
  
  <p>My problem is with creating and setting the varargs <code>SqlParameter</code> (these instances must be reflected also). I need to shoehorn a single parameter into an array to satisfy the varargs signature.</p>
  
  <p>In the following, class loading is omitted for brevity. But assume <code>Class&lt;?&gt; simpleJdbcCallClass = SimpleJdbcCall.class</code>, etc.</p>
  
  <pre><code>Constructor sqlOutParameterConstructor =
      sqlOutParameterClass.getConstructor(String.class, int.class);
  Object sqlOutParameter = sqlOutParameterConstructor.newInstance(param, type);
  
  Object paramArray = Array.newInstance(sqlParameterArrayClass, 1);
  Array.set(paramArray, 0, sqlParameterClass.cast(sqlOutParameter));
  // IllegalArgumentException thrown above.
  // It is thrown without the call to .cast too.
  
  Method declareParametersMethod = 
      simpleJdbcCallClass.getMethod("declareParameters", sqlParameterArrayClass);
  declareParametersMethod.invoke(procedure, paramArray);
  </code></pre>
  
  <p>The exception thrown is:</p>
  
  <pre><code>java.lang.IllegalArgumentException: array element type mismatch
  at java.lang.reflect.Array.set(Native Method)
  </code></pre>
  
  <p>The method takes <code>SqlParameter ...</code> and I have an instance of a subclass <code>SqlOutParameter</code>. Hence I try to cast with <code>sqlParameterClass.cast(sqlOutParameter)</code>. The exception is thrown with or without this casting.</p>
  
  <p>Debugging I can confirm that <code>paramArray</code> is an <code>SqlParameter[]</code> and <code>sqlParameterClass.cast(sqlOutParameter)</code> is an <code>SqlOutParamter</code> (not <code>SqlParameter</code> as cast). I suspect this may be the problem.</p>