我想知道是否可以使用 Java 反射 API 更改类的整数数组的长度。如果是,怎么办?
最佳答案
没有;创建一个固定长度的数组。
您可以做的是通过在更大数组中使用副本修改字段的值来接近(使用Arrays.copyOf
) ,只要您知道这样修改不会导致任何不一致。
/* 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));
关于Java 反射 - 编辑数组长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12000604/