提示信息

Java高级应用之通过反射访问操作数组

藏匿 已关注

通过反射访问操作数组,可以使用java.lang.reflect.Array类中的一些方法来实现,下面是一个示例代码:

  1. import java.lang.reflect.Array;
  2. public class ArrayReflectionExample {
  3. public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
  4. int[] array = new int[]{1, 2, 3, 4, 5};
  5. // 通过反射获取数组类型
  6. Class<?> arrayType = array.getClass().getComponentType();
  7. // 获取数组长度
  8. int length = Array.getLength(array);
  9. // 获取数组中的元素
  10. for (int i = 0; i < length; i++) {
  11. int element = Array.getInt(array, i);
  12. System.out.println("Element at index " + i + ": " + element);
  13. }
  14. // 修改数组中的元素
  15. Array.setInt(array, 0, 10);
  16. // 输出修改后的数组元素
  17. for (int i = 0; i < length; i++) {
  18. int element = Array.getInt(array, i);
  19. System.out.println("Modified element at index " + i + ": " + element);
  20. }
  21. }
  22. }

以上代码中,我们首先通过getClass().getComponentType()方法获取了数组的类型,然后通过getLength()方法获取了数组的长度。接下来,我们使用getInt()方法来获取数组中的元素,并使用setInt()方法来修改数组中的元素。

运行以上代码,将输出如下结果:

  1. Element at index 0: 1
  2. Element at index 1: 2
  3. Element at index 2: 3
  4. Element at index 3: 4
  5. Element at index 4: 5
  6. Modified element at index 0: 10
  7. Modified element at index 1: 2
  8. Modified element at index 2: 3
  9. Modified element at index 3: 4
  10. Modified element at index 4: 5

可以看到,通过反射我们成功地访问和修改了数组中的元素。

    遇到难题? "AI大模型GPT4.0、GPT" 是你的私人解答专家! 点击按钮去提问......
藏匿 关注 已关注

最近一次登录:2023-10-09 13:11:52   

暂时还没有签名,请关注我或评论我的文章
×
免费图表工具,画流程图、架构图