Follow Up: Create an an array of objects from clas

2019-08-31 06:25发布

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()[];

4条回答
劳资没心,怎么记你
2楼-- · 2019-08-31 06:49

Try:

Class<?> c = Class.forName(className);
Object xyz = Array.newInstance(c, length);
查看更多
Emotional °昔
3楼-- · 2019-08-31 06:53

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楼-- · 2019-08-31 07:06
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.

查看更多
劳资没心,怎么记你
5楼-- · 2019-08-31 07:11

Use Array:

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

and catch the appropriate exceptions.

查看更多
登录 后发表回答