I find that there is a lack of examples of how to use a lot of these very helpful functions in https://chaquo.com/chaquopy/doc/current/python.html#java.cast.
I would appreciate more examples showcasing how to perform some tasks I have struggled to perform. Such as explaining whether it is possible to convert 2-d Java arrays to Python lists, arrays, or tensors. And even just understanding what the syntax is for using java.cast().
In Java — and therefore in the java
module that you link to — a "cast" doesn't actually convert an object from one runtime-type to another.1 Rather, it merely converts an expression from one static type to another; and it only works if the object's runtime-type already is either that static type, or a subtype of it, or null
(None
).
That's why the java.cast
documentation says "The object must either be assignable to the given class, or None
(representing Java null
), otherwise TypeError
will be raised."
So you can't use java.cast
to do any of the tasks you've mentioned. A Java array isn't a Python list, isn't a Python array, and isn't a Python tensor, so you can't just "cast" it to be one.
Relatedly, the documentation says that "The class must be one created by jclass
or jarray
, or a JNI type signature for a class or array." So there's no way to even express the idea of "cast to a Python list".
1. Note: Java actually has two kinds of "casts": in addition to the one for objects that I'm talking about here, there's also one for numeric primitives, whereby (for example) ((int) 3.5)
is 3
. That one really does do a value conversion, but it only applies to the seven numeric types byte
, short
, int
, long
, char
, float
, and double
.