[Python] py4j的使用

py4j简介:

官网
Py4J enables Python programs running in a Python interpreter to dynamically access Java objects in a Java Virtual Machine. Methods are called as if the Java objects resided in the Python interpreter and Java collections can be accessed through standard Python collection methods. Py4J also enables Java programs to call back Python objects.

Mac安装:

  • pip 安装
pip install py4j

py4j.jar包路径:/usr/share/py4j/py4j0.x.jar or /usr/local/share/py4j/py4j0.x.jar
  • conda 安装(或者使用Anaconda-Navigator安装)
conda install py4j

py4j.jar包路径:/anaconda3/share/py4j/py4j0.x.jar

使用:

1.java代码

// 需要导入py4j.jar包
import py4j.GatewayServer;
import java.util.Random;


public class EntryPoint {
    private static final Random random = new Random();

    public int randInt() {
        return random.nextInt();
    }

    public static void main(String[] args) {

        EntryPoint app = new EntryPoint();
        // py4j服务
        GatewayServer gatewayServer = new GatewayServer(app);
        gatewayServer.start();
        System.out.println("Gateway Server Started");
    }
}

2.Python代码

from py4j.java_gateway import JavaGateway

# 初始化
gateway = JavaGateway()

def main():
    # 调用Java-EntryPoint中的randInt函数
    a = gateway.entry_point.randInt()
    print(a)

if __name__ == '__main__':
    main()
注意:
1.导入py4j.jar包
2.运行Java代码
3.运行Python代码(必须在2之后)

python调用Java的其他方式:

感谢ayuLiao的这篇文章python调用Java的多种方法

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 928 4:30开始心房颤抖 昏迷 无法吸痰 白沫 胸腔积液 眼珠水肿 守夜 927 表征平稳 医生说心率变慢 口...
    海蛎子屁屁阅读 157评论 0 0
  • 在一座古老的寺庙里新来了一个小和尚,小和尚做事很积极,刚来便跑到师父身边诚恳的说:“师父,我初来乍到,先干些什么呢...
    易己净心阅读 521评论 2 3