Java反射学习三

反射与数组

  

  java.lang.Array类提供了动态创建和访问数组元素的各种静态方法。

  例程ArrayTester1类的main()方法创建了一个长度为10的字符串数组,接着把索引位置为5的元素设为“hello”,然后再读取索引位置为5的元素的值。

  

复制代码
import java.lang.reflect.Array;

public class ArrayTester1
{
    public static void main(String[] args) throws Exception
    {
        Class<?> classType = Class.forName("java.lang.String");
        
        //生成数组,指定元素类型和数组长度
        Object array = Array.newInstance(classType, 10);
        
        Array.set(array, 5, "hello");
        String str = (String)Array.get(array, 5);
        
        System.out.println(str);
                
    }

}
复制代码

多维数组

      首先,区别一下下面两者:

 

  System.out.println(Integer.TYPE);

   System.out.println(Integer.class);

 

  输出:

  int

  class java.lang.Integer

 

  一个多维数组的程序实例:

  

复制代码
import java.lang.reflect.Array;

public class ArrayTester2
{
    public static void main(String[] args)
    {
        int[] dims = new int[] { 5, 10, 15 };

        // 注意区分下面两种
        System.out.println(Integer.TYPE);    // int
        System.out.println(Integer.class);    // Integer

        // 创建一个三维数组,这个数组的三个维度分别是5,10,15
        Object array = Array.newInstance(Integer.TYPE, dims);
        // 可变参数,也可以这样写:
        // Object array = Array.newInstance(Integer.TYPE, 5,10,15);

        System.out.println(array instanceof int[][][]);
        
        Class<?> classType0 = array.getClass().getComponentType();    // 返回数组元素类型
        System.out.println(classType0);    // 三维数组的元素为二维数组,输出:class [[I

        // 获得第一层的索引为3的数组,返回的是一个二维数组
        Object arrayObject = Array.get(array, 3);
        Class<?> classType = arrayObject.getClass().getComponentType();    // 返回数组元素类型
        System.out.println(classType);    // 二维数组的元素为一维数组,输出:class [I

        // 此处返回的是一个一维数组
        arrayObject = Array.get(arrayObject, 5);
        Class<?> classType2 = arrayObject.getClass().getComponentType();    // 返回数组元素类型
        System.out.println(classType2);    // 一维数组的元素为int

        // 给一维数组下标为10的位置设置值为37
        Array.setInt(arrayObject, 10, 37);

        int[][][] arrayCast = (int[][][]) array;
        System.out.println(arrayCast[3][5][10]);
    }

}
复制代码

参考资料:

http://www.cnblogs.com/mengdd/archive/2013/01/26/2878136.html

 http://www.cnblogs.com/gulvzhe/archive/2012/01/27/2330001.html

http://www.cnblogs.com/rollenholt/archive/2011/09/02/2163758.html

http://www.cnblogs.com/octobershiner/archive/2012/03/18/2404751.html


 

原文地址:https://www.cnblogs.com/upcwanghaibo/p/5654437.html