使用Py4j将Python对象发送到Java [英] Send a Python object to Java using Py4j

查看:415
本文介绍了使用Py4j将Python对象发送到Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过将Python对象发送到Java来扩展本教程中的示例.虽然在Python和Java之间交换String对象的示例代码运行良好,但是当我尝试用自己的Python对象(事件)替换它时,将显示关于object_id的错误.

I'm trying to extend the example from this tutorial by sending Python objects to Java. While the example code which exchanges String objects between Python and Java works fine, when I try to replace it with my own Python object (Event), an error regarding object_id is displayed.

Python代码:

class Event(object):
   #some content here

stack = gateway.entry_point.getStack()
event = Event()

stack.push(event)

错误:

Traceback (most recent call last):
  File "/home/******/src/py4jSample.py", line 19, in <module>
   stack.push(event)
  File "/usr/local/lib/python2.7/dist-packages/py4j-0.7-py2.7.egg/py4j/java_gateway.py", line 423, in __call__
    [get_command_part(arg, self.pool) for arg in new_args])
  File "/usr/local/lib/python2.7/dist-packages/py4j-0.7-py2.7.egg/py4j/protocol.py", line 241, in get_command_part
    command_part = REFERENCE_TYPE + parameter._get_object_id()
AttributeError: 'Event' object has no attribute '_get_object_id'

有什么想法可以解决吗?

Any idea how this can be solved?

推荐答案

问题是您无法将纯Python对象发送到Java端(在这种情况下,调用push实际上会调用Java方法"Stack.push").您只能发送(1)可自动转换为Java对象的对象(基元,例如int,字节数组,字符串),(2)从Java接收到的对象,例如堆栈",或(3)

the problem is that you cannot send pure Python objects to the Java side (in this case, calling push actually calls the Java method "Stack.push"). You can only send (1) objects that can be automatically converted to Java objects (primitives such as int, byte array, strings), (2) objects received from Java such as "stack", or (3) Python objects implementing a Java interface:

class Event(object):
    def myMethod(param1, param2):
        return "foo"

    class Java:
        implements = ['yourpackage.IEvent']

如果要发送实现Java接口的Python对象,则需要接受来自Python解释器的传入连接(如果调用Python方法,则JVM将回调Python解释器):

If you want to send Python objects implementing a Java interface, you need to accept incoming connections from the Python interpreter (the JVM will call back the Python interpreter if a Python method is called):

gateway = JavaGateway(start_callback_server=True)
stack = gateway.entry_point.getStack()
event = Event()
stack.push(event)

这篇关于使用Py4j将Python对象发送到Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆