Follow Up: Create an an array of objects from classname

喜欢而已 提交于 2019-12-25 03:04:40

问题


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


来源:https://stackoverflow.com/questions/1632130/follow-up-create-an-an-array-of-objects-from-classname

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!