Creates an `Instance` of the class `class_name`, passing an array of `InvocationArg`s to construct the instance.
(
&self,
class_name: &str,
inv_args: &[impl Borrow<InvocationArg>],
)
| 442 | |
| 443 | /// Creates an `Instance` of the class `class_name`, passing an array of `InvocationArg`s to construct the instance. |
| 444 | pub fn create_instance( |
| 445 | &self, |
| 446 | class_name: &str, |
| 447 | inv_args: &[impl Borrow<InvocationArg>], |
| 448 | ) -> errors::Result<Instance> { |
| 449 | debug(&format!( |
| 450 | "Instantiating class {} using {} arguments", |
| 451 | class_name, |
| 452 | inv_args.len() |
| 453 | )); |
| 454 | unsafe { |
| 455 | // Factory invocation - first argument: create a jstring to pass as argument for the class_name |
| 456 | let class_name_jstring: jstring = |
| 457 | jni_utils::global_jobject_from_str(class_name, self.jni_env)?; |
| 458 | |
| 459 | // Factory invocation - rest of the arguments: Create a new objectarray of class InvocationArg |
| 460 | let size = inv_args.len() as i32; |
| 461 | let array_ptr = { |
| 462 | let j = (opt_to_res(cache::get_jni_new_object_array())?)( |
| 463 | self.jni_env, |
| 464 | size, |
| 465 | cache::get_invocation_arg_class()?, |
| 466 | ptr::null_mut(), |
| 467 | ); |
| 468 | jni_utils::create_global_ref_from_local_ref(j, self.jni_env)? |
| 469 | }; |
| 470 | let mut inv_arg_jobjects: Vec<jobject> = Vec::with_capacity(size as usize); |
| 471 | |
| 472 | // Factory invocation - rest of the arguments: populate the array |
| 473 | for i in 0..size { |
| 474 | // Create an InvocationArg Java Object |
| 475 | let inv_arg_java = inv_args[i as usize] |
| 476 | .borrow() |
| 477 | .as_java_ptr_with_global_ref(self.jni_env)?; |
| 478 | // Set it in the array |
| 479 | (opt_to_res(cache::get_jni_set_object_array_element())?)( |
| 480 | self.jni_env, |
| 481 | array_ptr, |
| 482 | i, |
| 483 | inv_arg_java, |
| 484 | ); |
| 485 | inv_arg_jobjects.push(inv_arg_java); |
| 486 | } |
| 487 | // Call the method of the factory that instantiates a new class of `class_name`. |
| 488 | // This returns a Instance that acts like a proxy to the Java world. |
| 489 | let java_instance = (opt_to_res(cache::get_jni_call_static_object_method())?)( |
| 490 | self.jni_env, |
| 491 | cache::get_factory_class()?, |
| 492 | cache::get_factory_instantiate_method()?, |
| 493 | class_name_jstring, |
| 494 | array_ptr, |
| 495 | ); |
| 496 | |
| 497 | // Check for exceptions before creating the globalref |
| 498 | Self::do_return(self.jni_env, ())?; |
| 499 | |
| 500 | let java_instance_global_instance = |
| 501 | jni_utils::create_global_ref_from_local_ref(java_instance, self.jni_env)?; |