2

Given the following Java code:

int     x[] = new int[3];
Integer y[] = new Integer[3];

java.lang.reflect.Array.setInt(x, 0, 10);   // works as expected (i.e. x[0] = 
10)
java.lang.reflect.Array.setInt(x, 1, 20);   // works as expected (i.e. x[1] = 20)
java.lang.reflect.Array.setInt(x, 2, 30);   // works as expected (i.e. x[2] = 30)

java.lang.reflect.Array.setInt(y, 0, 10);   // throws an exception

java.lang.reflect.Array.setInt(y, 1, 20);   // throws an exception

java.lang.reflect.Array.setInt(y, 2, 30);   // throws an exception

Why can one use reflection to assign values to variable x, while it is not possible to do so for variable y?

2
  • 1
    Because y is an Integer[], and x is an int[]. Commented Mar 6, 2016 at 21:12
  • 3
    That method throws an exception "If the specified object argument is not an array, or if the specified value cannot be converted to the underlying array's component type by an identity or a primitive widening conversion". It doesn't handle boxing for you. Commented Mar 6, 2016 at 21:13

2 Answers 2

3

I would expect that to make it work with y, you will need to write

 java.lang.reflect.Array.set(y, 0, Integer.valueOf(10));

as reflection won't take care of boxing for you.

Sign up to request clarification or add additional context in comments.

Comments

2

This worked for me:

public class ArrayReflectionTest
{
   public static void main(String[] args) {
      Integer[] y = new Integer[3];
      java.lang.reflect.Array.set( y, 0, 10 );
      System.out.println( y[0] );
   }

}

Since 10 will be auto-boxed to an Integer, you don't have to explicitly convert it. However if your array is any type besides Integer, I think you will have to explicitly convert it (to Byte, Character, Long, etc.). I don't think object types will be converted in those cases.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.