Search code examples
javarmiclassnotfoundexception

RMI ClassNotFoundException


I've been building an RMI application over the past week and I've hit a roadblock that no amount of googling can seem to help with.

The following code is used to send an object from the server to the client via RMI:

Server code:

import rocks.Rock;
import rocks.squareRock;

import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class Server extends UnicastRemoteObject
        implements RemInterface {

    public Server() throws RemoteException {
        super();
    }

    public static void main(String argv[]) {
        try {
            Server serv = new Server();
            Naming.rebind("RockServer", serv);
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }

    public Rock getRock() {
        return new squareRock();
    }
}

Client code:

import rocks.Rock;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;

public class Client {
    RemInterface reminterface = null;

    public Client() {
        String strName = "rmi://127.0.0.1/RockServer";
        try {
            reminterface = (RemInterface) Naming.lookup(strName);
        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (NotBoundException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    public Rock loadRock() {
        try {
            return reminterface.getRock();
        } catch (Throwable t) {
            return null;
        }
    }
}

Interface:

public interface RemInterface {
    public Rock getRock() throws RemoteException;
}

In this situation:

  • The "Rock" class is available in both the Client and Server classpath.
  • The "Rock" class implements serializable.
  • The "squareRock" extends class rock and is only available in the server's classpath.

The error I get when trying to call a method using a Rock from loadRock() on the client is as follows:

STDERR: java.rmi.UnmarshalException: error unmarshalling return; nested exception is: 
java.lang.ClassNotFoundException: SquareRock

Any help would be appreciated.


Solution

  • You are returning an object of Type rocks.squareRock from the Server. During the de-serialization process at the client, this class will be required in order to create an instance of this class to represent the response from the server. As you've already indicated that the class is available only in the server's classpath, the failure to locate and load the said class causes the exception.

    The resolution will be to make the rocks.squareRock class available in the client as well.