Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array initialization using reflection

Someone please help to understand how can we initialize 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 array it is giving me exception.

java.lang.InstantiationException
like image 972
Java_Alert Avatar asked Jun 20 '13 12:06

Java_Alert


1 Answers

You can instantiate array like this:

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
    }
}
like image 66
anubhava Avatar answered Sep 28 '22 06:09

anubhava