views:

95

answers:

4

Hello,

I am following up on this question, 1268817

In the question, we find a way to create an isntance of an object given a the name (as a string) of the class.

But what about to create an array of those objects... how would one initialize that.

I was thinking something in the line of but doesnt seem to work

Object[] xyz = Class.forName(className).newInstance()[];
+1  A: 
Object objects = java.lang.reflect.Array.newInstance(Class.forName(classname), 10);

For an array of 10 elements.

Annoyingly it returns an object, instead of an object array.

As Tom points out, this is to allow:

Object objects = java.lang.reflect.Array.newInstance(int.class, 10);

An int[] is not assignable to an Object[], so the return type has to be an Object. But it is still annoying as you very rarely want to do this.

Yishai
That'll be because it can return an array of primitives.
Tom Hawtin - tackline
Tom, could you please elaborate on that? what is the significance of returning an array of primitives
bushman
@Bushman, he means that if you had it create an array if ints, that could not be assigned to an Object[] array, so the method has to return Object, and not Object[].
Yishai
+2  A: 

Use Array:

Object[] xyz = Array.newInstance(Class.forName(className), 123);

and catch the appropriate exceptions.

cletus
You will need a cast in there.
Tom Hawtin - tackline
A: 

Try:

Class<?> c = Class.forName(className);
Object xyz = Array.newInstance(c, length);
Andy
+1  A: 

Here is an example creating an array of String:

// equiv to String strArray = new String()[10]

Class cls = Class.forName("java.lang.String");
String[] strArray = (String[]) Array.newInstance(cls, 10);