我正在尝试关注Oracle网站上的this array reflection tutorial,这似乎不起作用。由于这是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中,2d数组基本上只是嵌套数组,因此理论上它应该可行。我错过了什么吗?
谢谢!
答案 0 :(得分:3)
我猜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]);
}
}