溫馨提示×

java怎么調用python類方法

小億
109
2023-12-05 00:21:20
欄目: 編程語言

在Java中調用Python類方法需要借助于Jython庫。Jython是一個將Python代碼解釋執行的Java實現。

以下是一個示例代碼,演示如何在Java中調用Python類方法:

  1. 首先,確保你已經安裝了Jython??梢詮腏ython官方網站下載Jython壓縮包,并將其解壓縮到合適的位置。

  2. 創建一個Java項目,并將Jython庫添加到classpath中。

  3. 創建一個名為PythonCaller.java的Java類,編寫以下代碼:

import org.python.util.PythonInterpreter;

public class PythonCaller {
    public static void main(String[] args) {
        PythonInterpreter interpreter = new PythonInterpreter();

        // 導入python模塊
        interpreter.exec("from example import MyClass");

        // 創建Python類實例
        interpreter.exec("my_object = MyClass()");

        // 調用Python類方法
        interpreter.exec("result = my_object.my_method()");

        // 獲取Python方法返回值
        String result = interpreter.get("result").toString();
        System.out.println("Python方法返回值: " + result);

        // 關閉Python解釋器
        interpreter.close();
    }
}
  1. 創建一個名為example.py的Python模塊,編寫以下代碼:
class MyClass:
    def my_method(self):
        return "Hello from Python"
  1. 運行Java程序,你將看到輸出結果為:Python方法返回值: Hello from Python。

這樣就實現了在Java中調用Python類方法的功能。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女