astonbitecode / j4rs

Java for Rust
Apache License 2.0
641 stars 36 forks source link

Array as argument #132

Closed dcz-self closed 3 weeks ago

dcz-self commented 3 weeks ago

I tried to use the library to call a simple function, but I'm stuck on arrays.

As soon as one is involved, the signatures seem to not match:

    let t = InvocationArg::try_from(vec![0.0_f64, 1.0_f64, 3.6_f64].as_slice())?;
    let str_instance = jvm.invoke_static("java.util.Arrays", "toString", &[InvocationArg::from(t)])?;

gives:

Exception in thread "main" org.astonbitecode.j4rs.errors.InvocationException: Error while invoking method toString of Class java.util.Arrays
        at org.astonbitecode.j4rs.api.invocation.JsonInvocationImpl.invokeStatic(JsonInvocationImpl.java:87)
Caused by: java.lang.NoSuchMethodException: Method toString was not found in java.util.Arrays or its ancestors.
        at org.astonbitecode.j4rs.api.invocation.JsonInvocationImpl.findMethodInHierarchy(JsonInvocationImpl.java:319)
        at org.astonbitecode.j4rs.api.invocation.JsonInvocationImpl.findMethodInHierarchy(JsonInvocationImpl.java:321)
        at org.astonbitecode.j4rs.api.invocation.JsonInvocationImpl.invokeMethod(JsonInvocationImpl.java:188)
        at org.astonbitecode.j4rs.api.invocation.JsonInvocationImpl.invokeStatic(JsonInvocationImpl.java:82)

When trying this on a custom class, the method is found and called as soon as I remove the array argument entirely.

What's the corrent way to pass an array (of primitives) to a method call?

astonbitecode commented 3 weeks ago

Have you tried what is mentioned here? Java arrays are created using Jvm.create_java_array.

dcz-self commented 3 weeks ago

Thanks, that went through.

I think I got confused about the docs.

First, I tried out Jvm.create_java_array("double", &[InvocationArg::try_from(0.0f64)?]), which failed (cannot create "double").

Then I tried InvocationArg::try_from(vec![0.0_f64, 1.0_f64, 3.6_f64].as_slice())? because the syntax looks highly sugared - so this is probably the simplest way to do this, right?

I think if there was a direct example of how to pass a double[] arg, I would have had no trouble.

Thanks for the help.

astonbitecode commented 3 weeks ago

Thanks @dcz-self . Would you be in any interest to send a PR about the example you would like to be in the documentation?

dcz-self commented 3 weeks ago

Sure, I just need another piece of info: what is this call for:

InvocationArg::try_from(vec![0.0_f64, 1.0_f64, 3.6_f64].as_slice())

If it doesn't create a double[], then what does it create? What is it useful for?

astonbitecode commented 3 weeks ago

InvocationArg::try_from(vec![0.0_f64, 1.0_f64, 3.6_f64].as_slice()) creates a List<Float> in Java. Essentially, all the Vecs in rust are transformed in List in Java.