javapythonjython

Passing java object to python


I am prototyping an interface to our application to allow other people to use python, our application is written in java. I would like to pass some of our data from the java app to the python code but I am unsure how to pass an object to python. I have done a simple java->python function call using simple parameters using Jython and found it very useful for what I am trying to do. Given the class below, how can I then use it in Python/Jython as an input to a function/class:

public class TestObject 
{
   private double[] values;
   private int length;
   private int anotherVariable;

   //getters, setters
 }

Solution

  • One solution. You could use some sort of message system, queue, or broker of some sort to serialize/deserialize, or pass messages between python and java. Then create some sort workers/producer/consumers to put work on the queues to be processed in python, or java.

    Also consider checking out for inspiration: https://www.py4j.org/

    py4j is used heavily by/for pyspark and hadoop type stuff.

    To answer your question more immediately.

    Example using json-simple.:

    import org.apache.commons.io.FileUtils;
    import org.json.simple.JSONObject;
     //import org.json.simple.JSONObject;
      
    
    public class TestObject 
    {
       private double[] values;
       private int length;
       private int anotherVariable;
       private boolean someBool;
       private String someString;
    
       //getters, setters
    
       public String toJSON() {
           JSONObject obj=new JSONObject();
           obj.put("values",new Double(this.values));
           obj.put("length",new Integer(this.length));
           obj.put("bool_val",new Boolean(this.SomeBool));
           obj.put("string_key",this.someString);
           StringWriter out = new StringWriter();
           obj.writeJSONString(out);
           return out.toString();
       }
    
       public void writeObject(){
              Writer writer = new BufferedWriter(
                                  new OutputStreamWriter(
                                      new FileOutputStream("anObject.json"), "utf-8")
                                  )
                               )
    
              writer.write(this.toJSON());
       }
    
       public static void setObject(){
           values = 100.134;
           length = 12;
           anotherVariable = 15;
           someString = "spam";
       }
     }
    

    And in python:

    class DoStuffWithObject(object):
        def __init__(self,obj):
            self.obj = obj
            self.changeObj()
            self.writeObj()
    
        def changeObj(self):
            self.obj['values'] = 100.134;
            self.obj['length'] = 12;
            self.obj['anotherVariable'] = 15;
            self.obj['someString'] = "spam";
    
        def writeObj(self):
            ''' write back to file '''
            with open('anObject.json', 'w') as f:
                json.dump(self.obj, f)
    
        def someOtherMethod(self, s):
           ''' do something else '''
           print('hello {}'.format(s))
    
    import json
    with open('anObject.json','r') as f:
        obj = json.loads(f.read())
    # print out obj['values'] obj['someBool'] ...
    for key in obj:
        print(key, obj[key])
    
    aThing = DoStuffWithObject(obj)
    aThing.someOtherMethod('there')
    

    And then in java read back the object. There are solutions that exist implementing this idea (JSON-RPC, XML-RPC, and variants). Depending, you may may also want to consider using something like ( http://docs.mongodb.org/ecosystem/drivers/java/ ) the benefit being that mongo does json.

    See:

    A more comprehensive list of queues:

    Resources referenced: