Search code examples
javapythonpython-2.7pyro

Pyro4: how to cast a list of tuples with Pyrolite in Java?


After installing Pyro4 and adding pyrolite and serpent jars to Java build path, using codes similar to the client and server side python codes which work OK with the Python client codes, I use some codes similar to the Java example on https://pythonhosted.org/Pyro4/pyrolite.html to access a Python server object.

import net.razorvine.pyro.*;

NameServerProxy ns = NameServerProxy.locateNS("127.0.0.1");
PyroProxy remoteobject = new PyroProxy(ns.lookup("example.greeting"));
List<String> inputWords = getExampleWords();
Object result = remoteobject.call("predictedResults", inputWords );
System.out.println("result = "+result );
remoteobject.close();
ns.close();

The printed python clent side result is similar to:

>> print 'result = \n' + str(result)

result =
[(u'aaa', 0.88877496454662064), (u'bbb', 0.019192749769012061), (u'?', 0.0070963814247323219), (u'ccc', 0.0068011253515576015), (u'home', 0.00148328236618)]

The data structure is a list of tuples, each of which a pair of string and float, like:

result = []
for i in xrange(10):
    result.append((list[i], value[i])) 

And the Java result printed on console is:

>> Object result = remoteobject.call("predictedResults", inputWords );
>> System.out.println("result = "+result );

result = [[Ljava.lang.Object;@2e0fa5d3, [Ljava.lang.Object;@5010be6, [Ljava.lang.Object;@685f4c2e, [Ljava.lang.Object;@7daf6ecc, [Ljava.lang.Object;@2e5d6d97]

The question is: how to succesfully cast 'Object result = remoteobject.call("predictedResults", inputWords );' to a list of pairs of string and float in Java?


Solution

  • After trial and error I finally found the answer:

    Object result = remoteobject.call("predictedResults", inputWords );
    System.out.println("result = " + result);
    
    ArrayList<Object[]> resultList = (ArrayList<Object[]>) result;
    for (Object element : resultList) {
        Object[] pair = (Object[]) element;
        System.out.println((String)pair[0] + ", " + (Double)pair[1]); 
    }