简体   繁体   中英

create a two dimensionla array with Java reflection using java.lang.reflect.Array.newInstance

I need to create a two dimensional array of type java.lang.String using the reflection method from JavaScript code which is running inside a java application (inside the rhino scripting engine). This array will be a return value (of a javaScript function) that is used from JavaCode after the function call.

function test() {
    var a = java.lang.reflect.Array.newInstance(?, ?);
    // fill the array
    return a;
}

I couldn't find the right parameters for the newInstance call to create a two diemnsional array of type String.

At the moment I'm working with a workaround, ie I create an (outer) array of type java.lang.Object of size x and inside a x-length loop a create multiple arrays of type java.lang.String each of size y which are assigned to the ''outer' array elements.

Is there an easier way?

All you have to do is fill in the class and dimensions:

var a = java.lang.reflect.Array.newInstance(String.class, x, y);

Read more in the javadoc for newInstance(Class<?> componentType, int... dimensions) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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