8

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
2
  • 1
    Can you provide the code that cause the exception? Commented Jun 20, 2013 at 12:41
  • In order to call newInstance() you must have a zero args constructor and I don't think Array meets that requirement... Commented Jun 20, 2013 at 12:43

2 Answers 2

16

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
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

To create array of l_dto_class items you need to get component class and pass it to newInstance method: Array.newInstance(l_dto_class.getComponentClass(), 5)
11

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

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

1 Comment

Note that you need to change test[3] to test[].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.