astonbitecode / j4rs

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

How can I check if an `Instance` is null? #107

Closed pickleburger closed 6 months ago

pickleburger commented 6 months ago

How can I check if an Instance returned by invoke is null?

astonbitecode commented 6 months ago

There is no one-liner for this... However, you could call Objects.isNull:

let maybe_null = jvm.invoke(&test_instance, "getNullInteger", InvocationArg::empty())?;
let is_null =
    jvm.invoke_static(
            "java.util.Objects", 
             "isNull", 
            &[InvocationArg::try_from(maybe_null)?])?;
let is_null: bool = jvm.to_rust(is_null)?;
assert_eq!(is_null, true);
pickleburger commented 6 months ago

Thanks! That works, although it would be nice if there is a simpler way. I'll leave it to you to decide. Closing the ticket.

astonbitecode commented 6 months ago

Hey this could fit in the new api Jvm::check_equals.

For example, in order to check that an instance is null, you could:

// let maybe_null = jvm.invoke(...)?;
let is_null = jvm.check_equals(&maybe_null, InvocationArg::try_from(Null::Integer)?)?;

Note that Null::Integer can be compared with any Instance, regardless its Rust type... check_equals checks for equality in the Java world (Object.equals).

You could try in v0.20.0 (currently master), maybe it is better than the verbose workaround.

pickleburger commented 6 months ago

Thanks! Will check it out