py4J的最简单示例

15 投票
1 回答
15413 浏览
提问于 2025-04-17 22:10

我在我的 conda 虚拟环境中用 pip 安装了 py4J,然后写了一个超级简单的例子 AdditionApplication.java 来测试 py4J,但是编译失败了,也就是说:

javac AdditionApplication.java

编译时提示 GatewayServer 没有定义。

我对 Python 很了解,但不幸的是对 Java 不太熟悉。我还需要提供什么呢?

public class AdditionApplication {

  public int addition(int first, int second) {
    return first + second;
  }

  public static void main(String[] args) {
    AdditionApplication app = new AdditionApplication();
    // app is now the gateway.entry_point
    GatewayServer server = new GatewayServer(app);
    server.start();
  }
}

如果这有关系,我安装的 Java 版本是:

java -version
java version "1.7.0_51"
Java(TM) SE Runtime Environment (build 1.7.0_51-b13)
Java HotSpot(TM) 64-Bit Server VM (build 24.51-b03, mixed mode)

更新 1

在文件顶部添加了 import py4j.GatewayServer; 后,我遇到了另一个错误:

package py4j does not exist

更新 2

pip install py4j 安装后,在 <PATH_TO_CONDA_ENVIRONMENT>/share/py4j/py4j0.8.1.jar 下留下了一个 jar 文件。我已经通过以下方式将它添加到我的类路径中:

javac -cp <PATH_TO_CONDA_ENVIRONMENT>/share/py4j/py4j0.8.1.jar AdditionApplication.java

然后输出了

AdditionApplication.class

我该怎么运行它呢?

最终更新和解决方案:

在应用了之前的修复后,我终于用以下命令运行了代码:

java -cp <PATH_TO_CONDA_ENVIRONMENT>/share/py4j/py4j0.8.1.jar AdditionApplication 

代码在后台运行。要测试它:

>>> from py4j.java_gateway import JavaGateway
>>> gateway = JavaGateway()                   # connect to the JVM
>>> random = gateway.jvm.java.util.Random()   # create a java.util.Random instance
>>> number1 = random.nextInt(10)              # call the Random.nextInt method
>>> number2 = random.nextInt(10)
>>> print(number1,number2)
(2, 7)
>>> addition_app = gateway.entry_point        # get the AdditionApplication instance
>>> addition_app.addition(number1,number2)    # call the addition method

1 个回答

6

py4j 包中导入 GatewayServer,这样在应用程序中就可以直接使用这个类,而不需要加上包名。

import py4j.GatewayServer;

撰写回答