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.
This class provides static methods to dynamically create and access Java arrays. It consists of only static methods and the methods of Object class. The methods of this class can be used by the class name itself.
Creating an Array Of Objects In Java – We use the Class_Name followed by a square bracket [] then object reference name to create an Array of Objects. Class_Name[ ] objectArrayReference; Alternatively, we can also declare an Array of Objects as : Class_Name objectArrayReference[ ];
As you have probably figured out by now, regular arrays in Java are of fixed size (an array's size cannot be changed), so in order to add items dynamically to an array, you need a resizable array. In Java, resizable arrays are implemented as the ArrayList class ( java. util. ArrayList ).
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With