Java Reflection - Editing Array Length

前端 未结 4 1564
灰色年华
灰色年华 2020-12-21 14:10

I was wondering if it is possible to change to change the length of a class\'s integer array using the Java Reflection API. If so, how?

4条回答
  •  春和景丽
    2020-12-21 15:00

    Nope; an array is created with a fixed length.

    What you can do is get close by modifying the value of the field with a copy in larger array (using Arrays.copyOf), so long as you know modifying like this won't cause any inconsistency.

    /* desired length */
    final int desired = ...;
    /* the instance of the object containing the int[] field */
    final Object inst = ...;
    /* the handle to the int[] field */
    final Field field = ...;
    field.set(inst, Arrays.copyOf((int[]) field.get(inst), desired));
    

提交回复
热议问题