rust调用java实现方法

(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:

main.rs:

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);
}
相关推荐
名字还没想好☜5 小时前
Go 并发实战:用 channel 实现 worker pool
java·数据库·后端·golang·go
人道领域5 小时前
【LeetCode刷题日记】贪心算法理论与实战:455.分发饼干最优解
java·开发语言·数据结构·算法·leetcode·贪心算法
_abab5 小时前
Java面试宝典:从基础到架构2
java·面试·架构
xin_yao_xin5 小时前
Conda 环境的 CUDA PATH 配置指南
开发语言·python·conda·cuda
he___H5 小时前
基于LCEL的联想
开发语言·python·langchain
万亿少女的梦1685 小时前
基于Spring Boot与Vue的繁星技术论坛系统设计与实现
java·spring boot·mysql·vue·系统设计
阿pin5 小时前
Android随笔-神经系统Handler
android·java·开发语言·handler
布朗克1686 小时前
Go 入门到精通-09-复合类型之Map
开发语言·后端·golang·map
zh_xuan6 小时前
c++ Expected用法
开发语言·c++·expected