Class uses Java reflection -Array

Additional articles about Java reflection: https://blog.csdn.net/ilo114/article/category/8633303
Needless to say we all know java.lang.Arrayis a type of Java reflection package array operations. Described in the documentation for the Array JavaSE8 of this to say:

The Array class provides static methods to dynamically create and access Java arrays.

Array class provides static methods to dynamically create and access Java arrays. Access is easy to understand, you can dynamically create a closer look.

Let's take a look at ###java.util.Arrays

  • Note that Arrays, believe that some small partners have used many times this type of tool, provides many convenient method of operation of the array we use.

  • Above that java.lang.Arrayis available to us static methods to dynamically create and access arrays. Let's look at the way Arrays copyOf is how to dynamically manipulate arrays of it.

    public static <T> T[] copyOf(T[] original, int newLength) {
        return (T[]) copyOf(original, newLength, original.getClass());
    }
    

    copyOf is used to doing it? Arrays main provider of this method to expand to the size of the array to array has been filled.

    You can use this

    User[] users = new User[10];
    ...//假如满了,给数组长度翻倍。
    users = Arrays.copyOf(users, users.length * 2);
    

    I do not know you have not noticed, this is a generic method returns the result. Its first parameter is the original array, the second parameter is the new length, returned by calling another overloaded copyOf方法, let's look at this overloaded copyOfmethod it.

    public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
        @SuppressWarnings("unchecked")
        T[] copy = ((Object)newType == (Object)Object[].class)
            ? (T[]) new Object[newLength]
            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }
    

    Inside the call is not difficult to understand that if passed Class and Object original objects come in an array of [] of the Class equal to it directly new Object[], if not equal, call java.lang.reflect.Arraythe newInstancemethod to create a new array, call followed by System.arraycopythe role of the method in the source code comments are: the Copies AN array from array at the Source specified, at the beginning AT specified position, to at the specified position of array at the Where do you want. means: start copying from the development of the position of the specified array to the specified location of the target array.

Why use reflection to achieve expansion array

  • We do not look at the reflection of realization"copyOf"

    private static Object[] badCopyOf(Object[] arr, int newLength) {
        Object[] newArray = new Object[newLength];
        System.arraycopy(arr, 0, newArray, 0, Math.min(arr.length, newLength));
        return newArray;
    }
    

    Without the above that Arraysthe copyOfmethod may be a lot of people will be directly above a little guilty write code. However, there is no thought of a problem, he can transition into correspondence with the class you want? Say, a MyObject[]class turn into Object[], and then turn back is possible, but from the beginning Object[]of the array can not be converted into MyObject[], this will throw ClassCastExceptionan exception, because the array is used new Object[length], Java array creation in the creation of Remember back when the type of each element, that is, newthe type of time.

  • So how strong we can turn it? See the following code

    private static Object goodCopyOf(Object arr, int newLength) {
      Class cls = arr.getClass();
      if (!cls.isArray()) {
          return null;
      }
      Object newArray = Array.newInstance(cls.getComponentType(), newLength);
      System.arraycopy(arr,0,newArray,0,Math.min(Array.getLength(arr), newLength));
      return newArray;
    }
    

    Read the above code, some small partners have doubts, why should object receives an array of objects, because the basic data types of arrays can not pass an array of objects, but can turn into objects

    double[] arr = {1.1, 1.2, 1.4, 12.2};
    arr = (double[]) goodCopyOf(arr, 10);
    

Objects within the array access

  • Array class provides several ways for us to use
static Object get(Object array, int index) Returns the element at the location
static XXX getXXX(Object array, int index) XXX is the basic type, ibid.
static void set(Object array, int index, Object value) Set specified position of the object
static void setXXX(Object array, int index, XXX z) Setting the specified position of the object, XXX basic data types
static Object newInstance(Class<?> componentType, int length) Create an array of objects.

More from Java SE * official documents https://docs.oracle.com/javase/8/docs/api/

The complete code is as follows

package io.ilss.reflection;

import java.lang.reflect.Array;
import java.util.Arrays;

/**
 * className ArrayTest
 * description ArrayTest
 *
 * @author feng
 * @version 1.0
 * @date 2019-01-29 23:42
 */
public class ArrayTest {
    public static void main(String[] args) {
        double[] arr = {1.1, 1.2, 1.4, 12.2};
        arr = (double[]) goodCopyOf(arr, 10);
        System.out.println(Arrays.toString(arr));

        String[] arr1 = {"aa", "bb", "cc"};
        arr1 = (String[]) goodCopyOf(arr1, 10);
        System.out.println(Arrays.toString(arr1));

        System.out.println("ClassCastException");
        arr1 = (String[]) badCopyOf(arr1, 20);
    }

    private static Object[] badCopyOf(Object[] arr, int newLength) {
        Object[] newArray = new Object[newLength];
        System.arraycopy(arr, 0, newArray, 0, Math.min(arr.length, newLength));
        return newArray;
    }

    private static Object goodCopyOf(Object arr, int newLength) {
        Class cls = arr.getClass();
        if (!cls.isArray()) {
            return null;
        }
        Object newArray = Array.newInstance(cls.getComponentType(), newLength);
        System.arraycopy(arr, 0, newArray, 0, Math.min(Array.getLength(arr), newLength));
        return newArray;
    }
}

Github relevant code: https://github.com/ilssio/java-base-ilss

Published 34 original articles · won praise 7 · views 8176

Guess you like

Origin blog.csdn.net/ilo114/article/details/86698141