发送一个Python对象使用Py4j Java来(Send a Python object to J

2019-08-07 18:10发布

我试图从扩展示例本教程通过发送Python对象到Java。 虽然其交换Python和Java之间的String对象的示例代码工作正常,当我试图用我自己的Python对象(事件)来代替它,则会显示有关的object_id错误。

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'

任何想法,这可怎么解决呢?

Answer 1:

问题是,你不能发送纯Python对象,Java端(在这种情况下,呼吁推动实际调用Java方法“Stack.push”)。 可以只发送(1)对象,可以被自动转换为Java对象(基元如int,字节数组,字符串),(2)从Java接收的对象,如“栈”,或(3) 的Python对象执行一个Java接口 :

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

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

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

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


文章来源: Send a Python object to Java using Py4j
标签: java python py4j