How can I instantiate an array of objects via reflection? For example, I have a Class X, and I want to instantiate X[10].

Chandra Patni

You can use newInstance(Class componentType, int length) method of java.lang.reflect.Array class to instantiate an array of objects. For example,

X array[] = (X [])Array.newInstance(X.class, 10);

will have the same effect as:

X array[] = new X[10];

Primitive arrays (for example an array of int) can also be instantiated similarly:

int array[] = (int [])Array.newInstance(int.class, 10);

will have the same effect as
int array[] = new int[10];
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact