简体   繁体   English

如何在 Java 中动态声明数组的形状?

[英]How to dynamically declare shape of an Array in Java?

I am working with an API where I need to provide a Object[] , Object[][] , Object[][][] ... you get the idea.我正在使用一个 API,我需要在其中提供一个Object[]Object[][]Object[][][] ......你明白了。

Assume setFoo requires an Object[] , this is how I get it to work:假设setFoo需要一个Object[] ,这就是我让它工作的方式:

Object hello = "Hello";
Object world = "world";

final List<Object> objects = new ArrayList<>();
objects.add(hello);
objects.add(world);

// {"Hello", "world"}
item.setFoo(objects.toArray());

And this is how I make Object[][] requirement work, so that I can call setBar ..这就是我如何使Object[][]需求工作,以便我可以调用setBar ..

Object hello = "Hello";
Object world = "world";

// We now we need to stuff these into an Array of Arrays as in: {{Hello},{world}}
final List<Object> helloList = new ArrayList<>();
helloList.add(hello);

final List<Object> worldList = new ArrayList<>();
worldList.add(world);

final List<List<Object>> surroundingList = new ArrayList<>();
surroundingList.add(helloList);
surroundingList.add(worldList);

final Object[][] objects = new Object[surroundingList.size()][1];
for (int i = 0; i < surroundingList.size(); i++) {
    objects[i] = surroundingList.get(i).toArray();
}

item.setBar(objects);

The problem is, I am not able to figure out how to create the Object[][][] dynamically.. Is there a way to do this in Java?问题是,我无法弄清楚如何动态创建 Object[][][] .. 有没有办法在 Java 中做到这一点? If I can make this guy final Object[][] objects = new Object[surroundingList.size()][1];如果我可以让这家伙final Object[][] objects = new Object[surroundingList.size()][1]; dynamic I should be in good hands.动态我应该得到很好的掌握。

You can't do this with static code.你不能用静态代码做到这一点。 The Java syntax and (compile time) type system doesn't support the declaration or construction of arrays with indefinite dimensions. Java 语法和(编译时)类型系统不支持具有不确定维度的数组的声明或构造。

You can create arrays with arbitrary dimensions using reflection;您可以使用反射创建具有任意维度的数组; eg例如

int nosDimensions = 2;
Class<MyClass> clazz = MyClass.class;
Object array = java.lang.reflect.Array.newInstance(clazz, nosDimensions);

MyClass[][] typedArray = (MyClass[][]) array;  // just to show we can do it ...

But the problem is that if you go down the path, you are liable to end up:但问题是,如果你沿着这条路走下去,你很可能会得到:

  • doing lots of casting to types with definite dimensions (see typedArray above), and / or对具有确定维度的类型进行大量转换(请参阅上面的typedArray ),和/或

  • doing operations on the arrays using messy reflective code.使用凌乱的反射代码对数组进行操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM