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、效果展示