7

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 Code:

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?

4
  • Welcome to StackOverflow! The line that the error is being thrown on is nowhere in your example code. Where is that code? Commented Jan 22, 2013 at 1:31
  • Thanks David. The code "stack.push(event)" is where the error is generated. Commented Jan 22, 2013 at 1:42
  • Did you try adding an attribute to the object named _get_object_id? Commented Jan 22, 2013 at 1:55
  • @nickb Thanks. I just added a method _get_object_id and the error no longer occurs.However, when I try to print the object received in the Java class, it shows a Null value for the object. Commented Jan 22, 2013 at 2:06

1 Answer 1

6

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']

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That answers my concern. I'll look at (2) and (3) to exchange the data.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.