假设我得到了一个对象类和一个 int[]
描述我希望实例化(并使用)的多维数组的任意长度。到目前为止,我已经知道我可以使用 java.lang.reflect.Array.newInstance(Class<?> type, int... sizes)
,但那时我被困住了。换句话说,
Class<?> type = float.class; // this varies (I receive this)
int[] sizes = new int[]{ 10, 400, 300 }; // this varies too, it could be e.g. int[]{0} for a scalar
Object o = (Object) java.lang.reflect.Array.newInstance(type, sizes);
定义Object o
之后我不知道如何进行。先验的,不知道有没有type
将是 float.class
或其他类型(现在我假设它是基本类型)。更糟糕的是,int[] sizes
可以是任何东西。
为了使其成为一个更具体的问题,我应该如何设置多维数组的每个元素 o
对于给定的值,比如 5.6
在我用 Array.newInstance
实例化它之后?
最佳答案
好问题。这真的很棘手,因为似乎没有办法将对象转换为给定维度的数组。我找不到从创建的实例中获取适当的多维数组对象的方法。但是如果你只是想获取和设置创建的数组中的元素,你可以使用下面的方法:
public static void main(String[] args) {
Class<?> type = float.class; // this varies (I receive this)
int[] sizes = new int[] { 1, 3 }; // this varies too, it could be e.g.
// int[]{0} for a scalar
Object f = Array.newInstance(type, sizes);
set(f, new int[] { 0, 2 }, 3.0f);
if (f instanceof Object[])
System.out.println(Arrays.deepToString((Object[]) f));
else {
int l = Array.getLength(f);
for (int i = 0; i < l; ++i) {
System.out.print(Array.get(f, i) + ", ");
}
System.out.println();
}
}
public static void set(Object arr, int[] indexPath, Object value) {
if (arr instanceof Object[]) {
Object[] temp= (Object[]) arr;
for (int i = 0; i < indexPath.length - 2; ++i) {
temp = (Object[]) temp[indexPath[i]];
}
Array.set(temp[indexPath[indexPath.length - 2]],
indexPath[indexPath.length - 1], value);
} else {
Array.set(arr,
indexPath[0], value);
}
}
set
方法将索引设置为数组。所以 set(f, new int[] {0,0,1}, 3.0f);
基本上应该做 f[0][0][1] = 3.0f
编辑:添加了一个稍微丑陋的修复程序来处理一维数组
关于java - 在 Java 中使用多维动态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19358025/