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);
}
相关推荐
战血石LoveYY7 分钟前
Integer类型超限,导致数据异常
java·算法
李永奉7 分钟前
杰理可视化SDK开发-【BUG】配置“TWS两边同时按消息使能”功能后,按键单击功能无效失灵
开发语言·单片机·嵌入式硬件·物联网·bug
m0_6174939421 分钟前
Python OpenCV 透视变换(Perspective Transform)详解与实战
开发语言·python·opencv
程序猿编码33 分钟前
用C++从零开始造一个微型GPT,不借助任何第三方库
开发语言·c++·gpt·模型推理
普通网友1 小时前
pytest一些常见的插件
开发语言·python·pytest
苦瓜花1 小时前
【Kotlin】初入门
android·开发语言·kotlin
cndes1 小时前
给Miniconda换源,让包下载更迅速
开发语言·python
乐观的Terry1 小时前
1、为什么要自己造发布系统
java·spring boot·后端·spring cloud·架构
LuminousCPP2 小时前
C 语言集中实践全记录:顺序表 + 单链表原理实现与通讯录项目实战【附可运行源码】
c语言·开发语言·数据结构·经验分享·笔记
兰令水2 小时前
hot100【acm版】【2026.7.13打卡-java版本】
java·开发语言·数据结构·算法·leetcode·面试