使用Py4j将Python对象发送到Java

时间:2013-01-22 01:30:19

标签: java python py4j

我正在尝试通过将Python对象发送到Java来扩展this tutorial的示例。虽然在Python和Java之间交换String对象的示例代码工作正常,但当我尝试用我自己的Python对象(Event)替换它时,会显示有关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'

知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:5)

问题是你不能将纯Python对象发送到Java端(在这种情况下,调用push实际上调用Java方法“Stack.push”)。您只能发送(1)可以自动转换为Java对象的对象(基本体,如int,字节数组,字符串),(2)从Java接收的对象,如“堆栈”,或(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解释器):

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