java调用python简单函数接口的具体教程

1、在java里面引入python依赖包

<!--        直接在java里面写python代码、在java中调用python脚本-->
        <dependency>
            <groupId>org.python</groupId>
            <artifactId>jython-standalone</artifactId>
            <version>2.7.0</version>
        </dependency>

2、编写相关代码测试一下

//testJavaAndPython.py
def add(a,b):
    return a + b

//Java_Python_test.java
package com.example.fuwu001.test;

import org.python.core.PyFunction;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;

public class Java_Python_test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.execfile("E:\\Data\\Code\\pythonProject\\test20240306\\003\\testJavaAndPython.py");

        // 第一个参数为期望获得的函数(变量)的名字,第二个参数为期望返回的对象类型
        PyFunction pyFunction = interpreter.get("add", PyFunction.class);
        int a = 5, b = 10;
        //调用函数,如果函数需要参数,在Java中必须先将参数转化为对应的“Python类型”
        PyObject pyobj = pyFunction.__call__(new PyInteger(a), new PyInteger(b));
        System.out.println("the anwser is: " + pyobj);
    }
}

3、效果展示

posted @ 2024-03-14 19:52  yesyes1  阅读(134)  评论(0编辑  收藏  举报