Java 反射 - 编辑数组长度 [英] Java Reflection - Editing Array Length

查看:43
本文介绍了Java 反射 - 编辑数组长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以使用 Java 反射 API 更改类的整数数组的长度.如果是这样,如何?

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?

推荐答案

Nope;创建一个固定长度的数组.

Nope; an array is created with a fixed length.

可以做的是通过在更大数组中使用副本修改字段的值来接近(使用Arrays.copyOf),只要你知道这样修改不会造成任何不一致.>

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));

这篇关于Java 反射 - 编辑数组长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆