Java reflection using the Array

1. What is Array

Array is a shorthand class, fully qualified class name is java.lang.reflect.Array.

What is the use 2.Array

Array can represent all of the array, you can dynamically create and modify elements inside pass Array.

3.Array use examples

(1) create

Use the static method newInstance () constructor Object object as follows:

public static Object newInstance(Class<?> element, int ... length);

The first parameter is representative of the class of elements, the remaining parameter indicates the number of dimensions, showing a one-dimensional array parameter, two parameters of said length dimension parameter value represents the number of two-dimensional array (an array of arrays).

Object intArray = Array.newInstance(int.class,3);              //int [3]
Object stringArray = Array.newInstance(String.class,2,3);      //String [2][3]

(2) Assignment

Assignment using static method set all the parameters returned by the Object object Array, a value corresponding to the index.

public static void set(Object array,int index,Object value);
public static void setBoolean(Object array,int index,boolean b);
public static void setXxxx(Object array,int index,xxx);

Wherein a represents the last substantially corresponding to the type, as an example of the second type of boolean.

Array.set(intArray,2,3);
Array.set(stringArray,1,new String[]{"123","456"});

(3) obtain the value

Use the static method get, parameters Array Returns Object object and index.

public static Object get(Object array,int index);
public static boolean getBoolean(Object array,int index);
public static xxx getXxx(Object array,int index);

The last substantially corresponding to the type represented, as an example of the second type of boolean

System.out.println(Array.get(intArray,2));
System.out.println(Array.get(Array.get(stringArray,1),1));

(4) cast

Array can return by cast Object object into a corresponding array.

var castIntArray = (int [])intArray;
var castStringArray = (String [][])stringArray;

Such an array can be used as a general use.

4. The complete code

import java.lang.reflect.*;

public class test
{
    public static void main(String[] args) {
        var intArray = Array.newInstance(int.class, 3);
        var stringArray = Array.newInstance(String.class, 2,3);
        Array.set(intArray, 2, 3);
        Array.set(stringArray, 1, new String[] { "123", "456" });

        System.out.println(Array.get(intArray, 2));
        System.out.println(Array.get(Array.get(stringArray,1),1));

        System.out.println("-------cast-------");
        System.out.println(((int[]) intArray)[2]);
        System.out.println(((String [][])stringArray)[1][1]);
    }
}

5. Run results

Here Insert Picture Description

Published 46 original articles · won praise 4 · Views 4080

Guess you like

Origin blog.csdn.net/qq_27525611/article/details/102741499