The use of java reflection Array

Keywords: Java

1. What is Array

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

2. What is the use of array

Array can represent all arrays, and can dynamically create and modify elements through array.

3.Array usage example

(1) create

Use the static method newInstance() to construct the Object object. The method is as follows:

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

The first parameter is the class representing the element, the remaining parameter represents the dimension, one parameter represents the one-dimensional array, two parameters represent the two-dimensional array (array of array), and the value of the parameter represents the length of the dimension.

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

(2) assignment

The static method set is used for assignment. The parameter is the Object object Object returned by Array, the subscript and the corresponding value.

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

The last represents the corresponding basic type, and the second is an example of boolean type.

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

(3) get value

The static method get is used, and the parameters are the Object object Object and subscript returned by Array.

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 represents the corresponding basic type, and the second is an example of boolean type.

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

(4) cast

You can convert the Object object returned by Array to the corresponding Array by casting.

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

This can be used as a normal array.

4. 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. Operation results

The following is the author's public number, welcome to pay attention.

Posted by HSKrustofsky on Fri, 25 Oct 2019 14:31:11 -0700