Reputation: 1652
We all know we can create an object with the help of class name in the string format. Like i have a class name "Test". Using
Class.forName("Test").newInstance()
We can create the object of that class.
My question is that is there any way to create an array or array list of the objects using class name ?? OR lets suppose we have an object of the class and can with this object we create the array or array list of the that object.
Upvotes: 10
Views: 16982
Reputation: 1500555
To create an array, you can use java.lang.reflect.Array
and its newInstance
method:
Object array = Array.newInstance(componentType, length);
Note that the return type is just Object
because there's no way of expressing that it returns an array of the right type, other than by making it a generic method... which typically you don't want it to be. (You certainly don't in your case.) Even then it wouldn't cope if you passed in int.class
.
Sample code:
import java.lang.reflect.*;
public class Test {
public static void main(String[] args) throws Exception {
Object array = Array.newInstance(String.class, 10);
// This would fail if it weren't really a string array
String[] afterCasting = (String[]) array;
System.out.println(afterCasting.length);
}
}
For ArrayList
, there's no such concept really - type erasure means that an ArrayList
doesn't really know its component type, so you can create any ArrayList
. For example:
Object objectList = new ArrayList<Object>();
Object stringList = new ArrayList<String>();
After creation, those two objects are indistinguishable in terms of their types.
Upvotes: 18
Reputation: 49372
You can use Array
Object xyz = Array.newInstance(Class.forName(className), 10);
It has a method newInstance(Class, int):
Creates a new array with the specified component type and length. Invoking this method is equivalent to creating an array as follows:
int[] x = {length};
Array.newInstance(componentType, x);
Upvotes: 6