Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are essentially two ways to do this:</p> <p>You could continue down your current path and use reflection to construct the classes:</p> <pre><code>public void addIndividualsOfType(Class&lt;? extends Individual&gt; clazz){ for (ListIterator it = indiList.listIterator(); it.hasNext(); ){ it.next() it.add(clazz.newInstance()); // using no-args constructor } } </code></pre> <p>and to use a constructor with arguments you'd replace<code>it.add(clazz.newInstance())</code> with something like this:</p> <pre><code> Constructor&lt;? extends Individual&gt; cons = clazz.getConstructor( param1.getClass(), param2.getClass(), param3.getClass()); it.add(cons.newInstance(param1, param2, param3)); </code></pre> <p>(I've left out the exception handling ... but you get the picture.)</p> <p>However, an altogether better approach would be to refactor your code so that you passed in a factory object rather than a <code>Class</code> object. For example:</p> <pre><code>public interface IndividualFactory { public Individual create(T1 p1, T2 p2, T3 p3); } public static final IndividualFactory TALL_FACTORY = new IndividualFactory() { public Individual create(T1 p1, T2 p2, T3 p3) { return new TallIndividual(p1, p2, p3); } }; public void addIndividualsOfType(IndividualFactory factory){ for (ListIterator it = indiList.listIterator(); it.hasNext(); ){ it.next() it.add(factory.create(param1, param2, param3); } } </code></pre> <p>Note that the factory-based solution can be statically type-checked. By contrast, the reflective version has to deal with a number of type-related runtime exceptions.</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