Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As the type of <code>args</code> is an <code>ArrayList&lt;Object&gt;</code>, you're not avoiding the boxing anyway:</p> <pre><code>// This code... float v = (Float)elem.get(names[i]); arg.add(v); // Will actually be equivalent to: float v = (Float)elem.get(names[i]); Float boxed = v; arg.add(boxed); </code></pre> <p>If the point is to call a constructor by reflection, then you're going to <em>have</em> to pass in a <code>Float</code> for any <code>float</code> parameters - that's just how it works.</p> <p>So basically, change <code>float.class</code> to <code>Float.class</code> and it should all work fine. EDIT: Ah, except then the <code>par</code> list will have the wrong type. Basically you want to <em>cast</em> with <code>Float.class</code>, but <em>add</em> <code>float.class</code> to the list of parameter types.</p> <p>You probably want a map from primitive types to wrapper types, like this:</p> <pre><code>private static final Map&lt;Class&lt;?&gt;&gt;, Class&lt;?&gt;&gt; PRIMITIVE_TYPE_MAP = buildPrimitiveTypeMap(); private static Map&lt;Class&lt;?&gt;&gt;, Class&lt;?&gt;&gt; buildPrimitiveTypeMap() { Map&lt;Class&lt;?&gt;&gt;, Class&lt;?&gt;&gt; map = new HashMap&lt;Class&lt;?&gt;&gt;, Class&lt;?&gt;&gt;(); map.put(float.class, Float.class); map.put(double.class, Double.class); // etc return map; } </code></pre> <p>Then:</p> <pre><code>String names[] = { "x", "y", "src" }; Class types[] = { float.class, float.class, String.class }; for (int i = 0; i &lt; names.length; i++) { if (elem.containsKey(names[i])) { par.add(types[i]); // For primitive types, only box to the wrapper type Class&lt;?&gt; castType = PRIMITIVE_TYPE_MAP.get(types[i]); if (castType == null) { castType = types[i]; } arg.add(castType.cast(elem.get(names[i]))); } } </code></pre> <hr> <p>In fact, if you trust that the values are of the right type already, I suspect you can just do:</p> <pre><code>arg.add(elem.get(names[i])); </code></pre> <p>After all, you're just casting to a particular type and then losing that type information again... using the <code>cast</code> call does perform a check that the execution-time types are correct though, so you may want to keep it for that reason.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload