Under difference circumstances, a Java RMI call might want to return either an entire object or just a reference of the object, similar to pass by value and pass by reference, respectively. I took me a very long time to figure out how to use different mechanism precisely in different cases. The other guides I found on the Internet, including the Sun's official guide, didn't provide details code-wise. This guide assumes the foundamentals of Java RMI, for example, creating interfaces etc.
First of all, primitive data types like int will be always returned as object.
Assume we have a remote class called SimpleService, which have a method called process that returns a class called SimpleReply. The interfaces are defined as following:
public interface ISimple extends Remote {
public ISimpleReply process() throws RemoteException;
}
public interface ISimpleReply extends Remote {
}
The implementation of ISimple is defined as following:
public class SimpleImpl extends UnicastRemoteObject implements ISimple {
public SimpleImpl() throws RemoteException { //explicit constructor to declare throws clause
super();
}
public ISimpleReply process() throws RemoteException {
return new SimpleReplyImpl();
}
}
The key part is the implementation of ISimpleReply. An implementation that will return object reference is shown below:
public class SimpleReplyImpl extends UnicastRemoteObject implements ISimpleReply {
private String signature = "This is some data."; //used to identify the object in network traffic
public SimpleReplyImpl() throws RemoteException {
super();
}
}
The implementation that will return object is show below:
public class SimpleReplyImpl implements Serializable, ISimpleReply {
private String signature = "This is some data."; //used to identify the object in network traffic
public SimpleReplyImpl() throws RemoteException {
super();
}
}
The difference is on the class definition. If the class is a sub class of UnicastRemoteObject, it is capable for serving RMI calls, hence a reference will be returned. If the class only implements Serializable, which is not capable for serving RMI calls, the object will be returned. If the class does not implement Serializable nor extend a class that implemented Serializable (e.g. UnicastRemoteObject), an exception will be thrown, and the client will get the exception.
Hope this guide is useful.
Comments
Post new comment