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);
}
相关推荐
励志的小陈6 小时前
贪吃蛇(C语言实现,API)
c语言·开发语言
QC班长6 小时前
Maven公司私库配置踩坑点
java·服务器·maven·intellij-idea
Makoto_Kimur6 小时前
java开发面试-AI Coding速成
java·开发语言
laowangpython6 小时前
Gurobi求解器Matlab安装配置教程
开发语言·其他·matlab
wengqidaifeng6 小时前
python启航:1.基础语法知识
开发语言·python
观北海6 小时前
Windows 平台 Python 极简 ORB-SLAM3 Demo,从零实现实时视觉定位
开发语言·python·动态规划
wuqingshun3141596 小时前
说说mybatis的缓存机制
java·缓存·mybatis
空中海7 小时前
Kubernetes 生产实践、可观测性与扩展入门
java·贪心算法·kubernetes
Devin~Y7 小时前
大厂Java面试实录:Spring Boot/Cloud、Kafka、Redis、K8s 与 Spring AI(RAG/Agent)三轮连环问
java·spring boot·redis·mysql·spring cloud·kafka·kubernetes
bLEd RING7 小时前
SpringBoot3.3.0集成Knife4j4.5.0实战
java