gpt4 book ai didi

java - py4J 最简单的例子

转载 作者:太空狗 更新时间:2023-10-29 19:25:32 44 4
gpt4 key购买 nike

我安装了 py4J在我的 conda 上使用 pip Python 中的虚拟环境。我写了一个 super 简单的例子 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留下一个jar <PATH_TO_CONDA_ENVIRONMENT>/share/py4j/py4j0.8.1.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

最佳答案

py4j包中导入GatewayServer,使不合格的类可以在应用中使用

import py4j.GatewayServer;

关于java - py4J 最简单的例子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22386399/

44 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com