Jump to content

Multiple distinct objects: Difference between revisions

(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 <E> getNNewObjects(int n, Class <? extends E> c){
List <E> ans = new LinkedList<E>();
try {
for(int i=0;i<n;i++)
ans.add(c.newInstance());//can't call new on generica classesclass object
} catch (InstantiationException e) {
e.printStackTrace();
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.