I have a question involving RMI, Serialization and runtime polymorphism.
I have an RMI server with below:
public interface Shape extends Remote, Serializable {
public double getArea() throws RemoteException;
}
public class Circle implements Shape {
double radius;
public Circle( double r) { radius = r; }
public double getArea() { return Math.PI * radius * radius; }
}
An object cObj of Circle class is registered in the RMI Registry:
Circle cObj = new Circle (10);
registry.bind("cObj", cObj);
Now, on the client side, I have the Shape.class file on the CLASSPATH, but it does not have Circle.class file on CLASSPATH.
Is it possible for the RMI client to perform below?
Shape obj = (Shape) registry.lookup("cObj");
obj.getArea();
Note that Circle.class is not in the CLASSPATH of the RMI client and the code on the client is not directly referencing the Circle class anyway. It is only referencing Shape interface type.
How I would look at this, may be the client performs a lookup and finds the object with cObj name, and Circle type. The server knows that Circle is a subtype of Shape, and serializes the object and sends it to the client. Now, I am not sure if the client can cast it into the superclass (Shape) type without having access to the Circle class definition.
Help appreciated.
If you don’t want to deploy the Circle class to the client you have two choices:
Use the RMI codebase feature. You need to look this up as it is far too large a topic to discuss here, but basically it makes classloading possible from an additional location dictated by the RMI server.
Make it an exported remote object, so that calls to it are also RMI calls. You’re halfway there already by making Shape extended Remote, but you also need to export Circle, either by making it extend UnicastRemoteObject or by calling UnicastRemoteObject.exportObject() with it on construction.
It seems to me that by extending Remote you really meant to do (2) all along. If you do this you don’t need to make Shape extend Serializable. If you don’t do (2) there is no point in having Shape extend Remote. You should remove one or the other: they are kind of mutually exclusive.