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);
}
相关推荐
长安er1 天前
LeetCode121/55/45/763 贪心算法理论与经典题解析
java·数据结构·算法·leetcode·贪心算法·贪心
心本无晴.1 天前
RAG技术详解:从原理到实战应用
开发语言·c#
墨白曦煜1 天前
Lombok 速查指南:从基础注解到避坑实录
java
ss2731 天前
线程安全三剑客:无状态、加锁与CAS
java·jvm·数据库
The Sheep 20231 天前
可视化命中测试
java·服务器·前端
电科_银尘1 天前
【Python/Pytorch】-- 创建 tiny-cuda-nn 环境
开发语言·pytorch·python
小小工匠1 天前
Vibe Coding - Claude Code 做 Java 项目 AI 结对编程最佳实践
java·结对编程·claude code
源码获取_wx:Fegn08951 天前
基于springboot + vue酒店预约系统
java·vue.js·spring boot·后端·spring
__万波__1 天前
二十三种设计模式(十九)--备忘录模式
java·设计模式·备忘录模式
郑泰科技1 天前
python虚拟环境实践:Conda 环境激活报错及解决
开发语言·python·conda