Multiple distinct objects: Difference between revisions
Content deleted Content added
add link to Delphi for pascal |
|||
Line 324: | Line 324: | ||
Generic version for class given at runtime: |
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.). |
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 |
<lang java5>public static <E> List<E> getNNewObjects(int n, Class<? extends E> c){ |
||
List |
List<E> ans = new LinkedList<E>(); |
||
try { |
try { |
||
for(int i=0;i<n;i++) |
for(int i=0;i<n;i++) |
||
ans.add(c.newInstance());//can't call new on |
ans.add(c.newInstance());//can't call new on a class object |
||
} catch (InstantiationException e) { |
} catch (InstantiationException e) { |
||
e.printStackTrace(); |
e.printStackTrace(); |