I'm using Java 11 (+ IntelliJ IDE). My code retrieves a multi-dimensional array through JNI from a 3d-party C++ library.
My code looks something like below:
Object[][][] param1 = {{{"somevalue"}}};
Object[] param2 = param1
Object[][][] param3 = (Object[][][])param2; //OK
Object[][][] result1 = SomeNativeLibrary.someNativeCall(param1);
Object someResult = result1[0][0][4]; //OK
Object[] result2 = result1;
Object[][][] result3 = (Object[][][])result2; //CastException
I can clearly see through my debugger that the structure of param1 and result1 are different (even though both are assumed to be three-dimensional arrays):
for param1: {Object[1][][]} -> {Object[1][]} -> {Object{1}}
for result1: {Object[1]} -> {Object[1]} -> {Object[4]}
Even though casting from param2 to param3 works without problem, casting from result2 to result3 fails with
"java.lang.CastException: class [Ljava.lang.Object; cannot be case to class [[[Ljava.lang.Object" (notice the single square-bracket versus triple square-bracket before the "L").
The problem I'm facing is that I return result1 through some remoting framework. So I end up (on the client/calling-side of the remoting) with a one-dimensional array like above result2.
1)How can I transform back result2 into a Object[][][] array so that I more readily access data?
2)Why is casting from param2 to param3 working but not result2 to result3?
Look up the documentation of SomeNativeLibrary.someNativeCall(param1)
, and check what it actually returns. The CastException shows that it is declared as a one-dimensional array of objects in the class file, so you need to treat it as such.
If it was a multidimensional C++ array originally, then it is likely that it is represented as a one-dimensional array in Java, with element (x,y,z)
at index x*Y*Z + y*Z + z
, where Y
is the dimension of the array in the y direction, and Z
the dimension in the z direction. But check the documentation to be sure, and use it in that manner.
A multi-dimensional array in Java is not structured like that, but as a one-dimensional array of pointers to other arrays. So you cannot directly cast it to a multi-dimensional Java array.
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.