Search code examples
javarmiclasscastexception

Java RMI Client experienced ClassCastException


I'm having trouble connecting my RMI client to the server. So I have these classes/interfaces :

    package application;

    import java.sql.ResultSet;

    public interface InterfaceRMI {

        public void insererEtudiant(String requete);
        public void supprimerEtudiant(String requete);
        public ResultSet selectionnerEtudiant(String requete);
    }

Server class :

    package application;

    import java.rmi.RemoteException;
    import java.rmi.server.UnicastRemoteObject;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;

    public class ServeurMySQL extends UnicastRemoteObject implements InterfaceRMI {

        public int port;

        public ServeurMySQL(int port) throws RemoteException {
            this.port = port;
        }


        @Override
        public void insererEtudiant(String requete) {
           // Implementation for insertion 
        }

        @Override
        public void supprimerEtudiant(String requete) {
          // Implementation for delete
        }

        @Override
        public ResultSet selectionnerEtudiant(String requete) {
            // Implementation for selection  
        }
    }

Connection test class :

    package application;

    import java.rmi.registry.LocateRegistry;
    import java.rmi.registry.Registry;

    public class test {

        public static void main(String[] args) {
             try {          
                Registry r = LocateRegistry.getRegistry(1098);

                InterfaceRMI serveur = (InterfaceRMI) (r.lookup("serveurMySQL"));

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

When I replaced the line InterfaceRMI serveur = (InterfaceRMI) (r.lookup("serveurMySQL")); by r.lookup("serveurMySQL"); I didn't get the Exception, I understood that the connection worked, and the problem was only the cast. But I don't know how to resolve it.

The exeption is as follows :

    java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast to application.InterfaceRMI
at application.test.main(test.java:13)

P.S: The RMI server is launched without any problem.


Solution

  • First:

     public interface InterfaceRMI 
    

    has to be

     public interface InterfaceRMI extends Remote
    

    Second:

    every method in your InterfaceRMI must declare throws RemoteException