user236501
user236501

Reputation: 8648

How do I implement a Marshalling class in Java?

I need to implement a Marshalling class in Java. Basically I understand Marshalling is use to format the data so that it can be send through socket network and then unmarshalling it on server side. Correct me if I am wrong thanks.

Then this 2 methods to complete.

public void marshallObject (Object obj, ObjectOutputStream stream); 
public Object unmarshallObject (ObjectInputStream stream); 

public void marshallObject(Object obj, ObjectOutputStream stream) {
    try {
        stream.writeObject(obj);
        stream.close();
    } catch (IOException e) {
        System.out.println("Exception:" + e); 
    }
}

public Object unmarshallObject(ObjectInputStream stream) {      
                Object object = null;
    try {
        object = stream.readObject();
    } catch (Exception e) {
        System.out.println("Exception:" + e);       }
    return obj;
}

I am using Java Object Serialization mechanism. However, using these in this simplistic method will not work, as Java serialization will not serialize the Remote References correctly. My lecturer mention I need to pass a stub containing a Remote Reference to the object instead. A remote object in this case will be the server. The true test that you are passing remote objects by reference and not by copy, is that the program need to be able to pass servers around and still be referring to the same object. I am quite blur with it, anybody can explain to me and guide me how to do?

Upvotes: 1

Views: 556

Answers (2)

user207421
user207421

Reputation: 310979

Your lecturer is mistaken. An exported remote object is automatically marshalled by RMI as its stub. There is nothing required of you to do here.

Upvotes: 0

Perception
Perception

Reputation: 80633

It's quite possible your lecturer wants you to find and use marshalled objects. They are part of the RMI API, and allow you to serialize objects while retaining remote references contained within them.

With a marshalled object your code would look more like this:

public void marshallObject(Object obj, ObjectOutputStream stream) {
    try {
        stream.writeObject(new MarshalledObject<Object>(obj));
        stream.close();
    } catch (IOException e) {
        System.out.println("Exception:" + e); 
    }
}

public Object unmarshallObject(ObjectInputStream stream) {      
    MarshalledObject<Object> object = null;
    try {
        object = stream.readObject();
    } catch (Exception e) {
        System.out.println("Exception:" + e);
    }
    return (object != null) ? object.get() : null;
}

Refer to the Javadoc for more information.

Upvotes: 1

Related Questions