Java – array initialization using reflection

Please help understand how we use reflection to initialize arrays in Java

For a simple object, we can do this:

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

But in the case of arrays, it gives me an exception

java.lang.InstantiationException

Solution

You can instantiate an 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
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>