(1)Cargo.toml 增加:
bash
j4rs = "0.18.0"
(2)java源码:
java
public class HelloWorld {
public static String sayHello(String name) {
return "Hello "+name;
}
}
编译:
javac HelloWorld.java
生成HelloWorld.class,设class所在目录是/tmp
(3)rust代码调用java:
rust
use j4rs::{ClasspathEntry, Instance, InvocationArg, Jvm, JvmBuilder};
fn main() {
let entry = ClasspathEntry::new("/tmp");
let jvm: Jvm = JvmBuilder::new().classpath_entry(entry).build().unwrap();
let parameter= "hello";
let result_instance= jvm
.invoke_static(
"HelloWorld", // The Java class to invoke
"sayHello", // The static method of the Java class to invoke
&[InvocationArg::try_from(parameter).unwrap()],
)
.unwrap();
let result: String = jvm.to_rust(result_instance).unwrap();
print!("{}", result);
}