使用 Class.cast 方法将伪装成对象的已知原始数组转换回其原始原始数组类型涉及到首先将操作分解为两个赋值,然后才能正确编译它的使用。
import java.util.Arrays;
class Scratch {
public static void main(String[] args) {
Object src = new int[]{1,2,3};
castAndSet(src);
}
// assign index i of src to dest after casting src to int[]
public static void castAndSet(Object src){
int[] dst = new int[]{4,5,6};
int i = 0; // assume array length greater than zero.
if(dst.getClass().equals(src.getClass())){ // assert both are same class
// src should also be an int[], so no ClassCastException to worry about
dst[i] = ((int[])src)[i]; //this works …Run Code Online (Sandbox Code Playgroud)