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);
}
相关推荐
临床数据科学和人工智能兴趣组3 小时前
在R语言中, 使用 as.factor() 函数转换数值型变量
开发语言·r语言
andyweike6 小时前
php笔记
开发语言·笔记·php
EatFan6 小时前
Spring Boot 4 落地观察:从 yudao-cloud、matecloud、JPower 看国产脚手架的升级路线与迁移清单
java·spring boot·后端·spring cloud·微服务·后端开发·jdk 21
Maiko Star6 小时前
* LangChain 提示词模板详解:ChatPromptTemplate 的使用与高级特性
java·人工智能·langchain
鬓戈6 小时前
Rust 语言与 AI 应用生态调研及学习路径
人工智能·学习·rust
Circ.7 小时前
Python 调试 Litellm 本地大模型接口:模型列表与对话接口实操踩坑记录
开发语言·python
现任明教教主~8 小时前
Thinkphp站群蜘蛛池SaaS系统YanyvSEO含多用户/积分/六大引擎计费/易支付对接
java·开发语言·spring
Zhou1411369 小时前
SpringSecurity_02_授权与高级功能
开发语言·python
一条破秋裤9 小时前
Linux 线程创建:pthread_create 与基本回收
java·linux·运维
布吉岛的石头9 小时前
Java 程序员第 49 阶段5:BERT 预训练目标 MLM+NSP 的工程含义
java·人工智能·深度学习·bert·transformer