简体   繁体   English

使用Py4j将Python对象发送到Java

[英]Send a Python object to Java using Py4j

I'm trying to extend the example from this tutorial by sending Python objects to Java. 我试图通过将Python对象发送到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和Java之间交换String对象的示例代码工作正常,但当我尝试用我自己的Python对象(Event)替换它时,会显示有关object_id的错误。

Python Code: Python代码:

class Event(object):
   #some content here

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

stack.push(event)

Error: 错误:

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? 知道如何解决这个问题吗?

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"). 问题是你不能将纯Python对象发送到Java端(在这种情况下,调用push实际上调用Java方法“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 : 您只能发送(1)可以自动转换为Java对象的对象(原语,如int,字节数组,字符串),(2)从Java接收的对象,如“stack”,或(3) 实现Java的Python对象界面

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

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM