Multiple distinct objects: Difference between revisions
Content added Content deleted
(add link to Delphi for pascal) |
|||
Line 324:
Generic version for class given at runtime:
It's not pretty but it gets the job done. The first method here is the one that does the work. The second method is a convenience method so that you can pass in a <tt>String</tt> of the class name. When using the second method, be sure to use the full class name (ex: "java.lang.String" for "String"). <tt>InstantiationException</tt>s will be thrown when instantiating classes that you would not normally be able to call <tt>new</tt> on (abstract classes, interfaces, etc.). Also, this only works on classes that have a no-argument constructor, since we are using <code>newInstance()</code>.
<lang java5>public static <E> List
List
try {
for(int i=0;i<n;i++)
ans.add(c.newInstance());//can't call new on
} catch (InstantiationException e) {
e.printStackTrace();
|