简体   繁体   中英

Java Reflection on an Integer Object

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 ?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM