Note that there are some explanatory texts on larger screens.

plurals
  1. POJava generic varargs method parameters
    primarykey
    data
    text
    <p>I am wondering if there is an easy, <strong>elegant</strong> and reusable way to pass a string and a string array to a method that expect varargs.</p> <pre><code>/** * The entry point with a clearly separated list of parameters. */ public void separated(String p1, String ... p2) { merged(p1, p2, "another string", new String[]{"and", "those", "one"}); } /** * For instance, this method outputs all the parameters. */ public void merged(String ... p) { // magic trick } </code></pre> <p>Even if all the types are consistent (<code>String</code>) I cannot find a way to tell to the JVM to <em>flatten</em> p2 and inject it to the merged parameter list?</p> <p>At this point the only way is to create a new array, copy everything into it and pass it to the function.</p> <p>Any idea?</p> <hr> <h2>EDIT</h2> <p>Base on your proposal here is the generic method I'll use: </p> <pre><code>/** * Merge the T and T[] parameters into a new array. * * @param type the destination array type * @param parameters the parameters to merge * @param &lt;T&gt; Any type * @return the new holder */ @SuppressWarnings("unchecked") public static &lt;T&gt; T[] normalize(Class&lt;T&gt; type, Object... parameters) { List&lt;T&gt; flatten = new ArrayList&lt;&gt;(); for (Object p : parameters) { if (p == null) { // hum... assume it is a single element flatten.add(null); continue; } if (type.isInstance(p)) { flatten.add((T) p); continue; } if (p.getClass().isArray() &amp;&amp; p.getClass().getComponentType().equals(type)) { Collections.addAll(flatten, (T[]) p); } else { throw new RuntimeException("should be " + type.getName() + " or " + type.getName() + "[] but was " + p.getClass()); } } return flatten.toArray((T[]) Array.newInstance(type, flatten.size())); } normalize(String.class, "1", "2", new String[]{"3", "4", null}, null, "7", "8"); </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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