0

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()[];
Community
  • 1
  • 1
bushman
  • 92
  • 8
  • completely outside the question -> "Follow Up" -- would be a nice feature on SO -- linking a questions with the follow up questions and/or answers -- and also let the previous people who asked and answered to know that a follow up has been initiated... – bushman Oct 27 '09 at 17:12
  • @bushman, checkout meta.stackoverflow.com, where you can post and discuss such suggestions. – Yishai Oct 27 '09 at 17:47

4 Answers4

2
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
  • 90,445
  • 31
  • 189
  • 263
2

Use Array:

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

and catch the appropriate exceptions.

cletus
  • 616,129
  • 168
  • 910
  • 942
1

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);
alphazero
  • 27,094
  • 3
  • 30
  • 26
0

Try:

Class<?> c = Class.forName(className);
Object xyz = Array.newInstance(c, length);
Andy
  • 8,870
  • 1
  • 31
  • 39