javaconcurrencyerlangjinterface

Send a list from Erlang to Java using JInterface


I'm writing a program requiring communication between Java and Erlang using JInterface. I've a problem with receiving a list from an Erlang process - somehow the object I get in Java is not a OtpErlangList but OtpErlangString and if I try to cast the received object to OtpErlangList, I get a cast exception. I've tried decoding the string, but it seems not to be the case.

It seems to me rather odd not be able to send a list from Erlang to Java, could you please take a look if I'm not making any basic mistake?

Java fragment:

OtpErlangObject erlangObject = mailbox.receive();
OtpErlangList erlangList = (OtpErlangList) erlangObject;
System.out.println(erlangList.toString());

Erlang fragment:

List = [1, 2, 3, 4],
JavaPid ! List

I'm omitting the rest of the code as I believe these are the lines where the problem is - I've tried it with other classses and it worked.


Solution

  • From Jinterface documentations:

    Lists in Erlang are also used to describe sequences of printable characters (strings). A convenience class OtpErlangString is provided to represent Erlang strings.

    Getting String

    For getting a string of printable characters in Java side, you should use stringValue() method which converts a list of integers into a Unicode string and returns a java.lang.String object.

    Erlang side:

    List = "hey" = [$h, $e, $y] = [104, 101, 121],
    JavaPid ! List
    

    Java side:

    OtpErlangObject erlangObject = mailbox.receive();
    OtpErlangList erlangList = (OtpErlangList) erlangObject;
    System.out.println(erlangList.stringValue());
    

    Getting Array

    For getting a list of elements in Java side, you should use elements() method which returns an array containing all of the list's elements. This way each element of array is an object of type OtpErlangObject.

    Erlang side:

    List = [1, 2, 3, 4],
    JavaPid ! List
    

    Java side:

    OtpErlangObject erlangObject = mailbox.receive();
    OtpErlangList erlangList = (OtpErlangList) erlangObject;    
    for(OtpErlangObject element : erlangList.elements()) {
        // do something with element
    }