pub unsafe fn JNI_CreateJavaVM_with_string_args<T: AsRef<str>>(
version: jint,
arguments: &[T],
ignore_unrecognized_options: bool,
) -> Result<(JavaVM, JNIEnv), jint>Expand description
Convenience function to call JNI_CreateJavaVM with a simple list of String arguments.
These arguments are almost identical to the command line arguments used to start the jvm with the java binary. Some options differ slightly. Consult the JNI Invocation API documentation for more information.
§Errors
JNI implementation specific error constants like JNI_EINVAL
§Panics
Will panic if the JVM shared library has not been loaded yet.
Will panic if more than jsize::MAX arguments are passed to the vm. (The JVM itself is likely to just die earlier)
If any argument contains a 0 byte in the string.
§Safety
The Safety of this fn is implementation dependant. On Hotspot JVM’s this fn cannot be called successfully more than once. Subsequent calls are undefined behaviour.
§Example
use std::ptr::null_mut;
use jni_simple::*;
//This example fn is roughly equivalent to "java -Xint -Xmx1G -Djava.class.path={absolute_path_to_jar_file} {main_class}" on the command line.
unsafe fn launch_jvm(absolute_path_to_jar_file: &str, main_class: &str) -> ! {
#[cfg(feature = "loadjvm")] //Only needed due to doctest!
load_jvm_from_java_home().expect("Failed to load jvm");
let (vm, env) = JNI_CreateJavaVM_with_string_args(JNI_VERSION_1_8, &[
"-Xint".to_string(),
"-Xmx1G".to_string(),
format!("-Djava.class.path={absolute_path_to_jar_file}")
], false).expect("Failed to start jvm");
let main_class = env.FindClass(main_class);
if env.ExceptionCheck() {
//Main class not found
env.ExceptionDescribe();
return std::process::exit(-1);
}
let main_method = env.GetStaticMethodID(main_class, "main","([Ljava/lang/String)V");
if env.ExceptionCheck() {
//no static main(String[] args) method in the main class.
env.ExceptionDescribe();
return std::process::exit(-1);
}
let string_class = env.FindClass("java/lang/String");
if env.ExceptionCheck() {
//Unlikely, java.lang.String not found.
env.ExceptionDescribe();
return std::process::exit(-1);
}
let main_method_string_parameter_array = env.NewObjectArray(0, string_class, null_mut());
if env.ExceptionCheck() {
//Unlikely jvm ran out of memory when creating "new String[0];"
env.ExceptionDescribe();
return std::process::exit(-1);
}
env.CallStaticVoidMethod1(main_class, main_method, main_method_string_parameter_array);
if env.ExceptionCheck() {
//Main method threw an exception
env.ExceptionDescribe();
return std::process::exit(-1);
}
//Block until all non deamon java threads the main method has started are done.
vm.DestroyJavaVM();
//Exit the process with success.
std::process::exit(0)
}