Array initialization using reflection

Someone please help to understand how we can initialize an array in java using reflection.

for a simple object we can do like this:

Class l_dto_class = Class.forName(p_fld.getType().getName()); Object l_dto_obj= l_dto_class.newInstance(); 

but for the case of an array, it gives me an exception.

 java.lang.InstantiationException 
+4
source share
2 answers

You can create an array as follows:

 if (l_dto_class.isArray()) { Object aObject = Array.newInstance(l_dto_class, 5); //5 is length int length = Array.getLength(aObject); // will be 5 for (int i=0; i<length; i++) Array.set(aObject, i, "someVal"); // set your val here } } 
+7
source

There is a class for the array in reflection java.lang.reflect.Array

 int[] test = (int[])Array.newInstance(int.class, 3); 
+7
source

Source: https://habr.com/ru/post/1487291/


All Articles