我正在尝试关注 this array reflection tutorial在 Oracle 的网站上似乎不起作用。由于这是 Oracle 自己的文档,我只是想知道我是否做错了什么:
Object matrix = Array.newInstance(int.class, 2);
Object row0 = Array.newInstance(int.class, 2);
Object row1 = Array.newInstance(int.class, 2);
Array.setInt(row0, 0, 1);
Array.setInt(row0, 1, 2);
Array.setInt(row1, 0, 3);
Array.setInt(row1, 1, 4);
Array.set(matrix, 0, row0); // <- This throws IllegalArgumentException
Array.set(matrix, 1, row1);
现在,我知道在 Java 中,二维数组基本上只是嵌套数组,所以理论上它应该可以工作。我错过了什么吗?
谢谢!
最佳答案
我猜 oracle 站点的代码是错误的
应该是
Object matrix = Array.newInstance(int.class, 2, 2);
代码
Object matrix = Array.newInstance(int.class, 2);
创建一个大小为 2 的数组,但数组对象必须是 int.class。
完整代码为:
import java.lang.reflect.Array;
import static java.lang.System.out;
public class CreateMatrix {
public static void main(String... args) {
Object matrix = Array.newInstance(int.class, 2, 2);//var arg was wrong in docs?
Object row0 = Array.newInstance(int.class, 2);
Object row1 = Array.newInstance(int.class, 2);
Array.setInt(row0, 0, 1);
Array.setInt(row0, 1, 2);
Array.setInt(row1, 0, 3);
Array.setInt(row1, 1, 4);
Array.set(matrix, 0, row0);
Array.set(matrix, 1, row1);
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
out.format("matrix[%d][%d] = %d%n", i, j, ((int[][]) matrix)[i][j]);
}
}
关于java - Object matrix = Array - Oracle网站实例上数组反射教程有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16065000/