Follow Up: Create an an array of objects from clas

2019-08-31 06:49发布

问题:

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:

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.



回答2:

Use Array:

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

and catch the appropriate exceptions.



回答3:

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);


回答4:

Try:

Class<?> c = Class.forName(className);
Object xyz = Array.newInstance(c, length);