Xuanwo commented on code in PR #2209:
URL:
https://github.com/apache/incubator-opendal/pull/2209#discussion_r1185755842
##########
bindings/java/src/macros.rs:
##########
Review Comment:
The main issue is that Java uses `exception` differently from Rust's
`Result` logic. To address this, we need to create a shim between the Rust and
Java code. For example:
- `xxx_inner() -> Result<T, Error>`
- `xxx() -> T`: This would call `xxx_inner()` and raise an exception.
Additionally, why do we need to build exceptions in Rust code? Could we
instead return a new object and raise an exception in Java?
j4rs returns a `jobject` for that:
```rust
#[call_from_java("io.github.astonbitecode.j4rs.example.RustFunctionCalls.addintegers")]
fn add_integers(integer_instance1: Instance, integer_instance2: Instance) ->
Result<Instance, String> {
let jvm: Jvm = Jvm::attach_thread().unwrap();
let i1: i32 = jvm.to_rust(integer_instance1).unwrap();
let i2: i32 = jvm.to_rust(integer_instance2).unwrap();
let sum = i1 + i2;
let ia = InvocationArg::try_from(sum).map_err(|error| format!("{}",
error)).unwrap();
Instance::try_from(ia).map_err(|error| format!("{}", error))
}
```
Underhood:
```rust
// The jni function return type
let ref jni_function_output = match &user_function_signature.output {
ReturnType::Default => ReturnType::Default,
_ => {
let ret_type: ReturnType = syn::parse_str("-> jobject").unwrap();
ret_type
}
};
// The jni return value. This may be void or jobject
let return_value = match &user_function_signature.output {
ReturnType::Default => {
let ret_value: Expr = syn::parse_str("()").unwrap();
ret_value
}
_ => {
let ret_value: Expr = syn::parse_str(
r#"match instance_to_return {
Ok(i) => {
i.java_object()
// i.as_java_ptr_with_local_ref(jni_env).unwrap()
},
Err(error) => {
let message = format!("{}", error);
let _ = jvm.throw_invocation_exception(&message);
ptr::null_mut()
},
}"#).unwrap();
ret_value
}
};
```
---
Binding must be simple and easy to understand.
If we have to add those complex logic, I prefer to use `j4rs` directly.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]