Java Reflection - Editing Array Length

前端 未结 4 1569
灰色年华
灰色年华 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 14:43

    An array is a fixed length data structure, so there is no way that it's length will be modified. Nevertheless, one can create a new array with a new fixed length in such way it can accommodate new members using

    System.arrayCopy()

    It is like you have an array of type T with the size of 2,

    T[] t1 = new T[2]

    and it is length is fixed with 2. So it can not store any more than 2 elements. But by creating new array with a new fixed length, say 5,

    T[] t2 = new T[5]

    So it can accommodate 5 elements now. Now copy the contents of the t1 to t2 using

    System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

    in this case of the example,

    System.arraycopy(t1, 0, t2, 0, t1.length)

    Now in the new array, you have position

    from t1.length to t2.length-1

    is available for you to use.

提交回复
热议问题