Search code examples
javainterfaceclientrmi

Java RMI client side


I'm trying to use the RMI Client-Server communication. I wrote the following class/interface:

  1. Interface RemoteInterface extends Remote
  2. Class HelloStub extends UnicastRemoteObject implements RemoteInterface
  3. Class Server, which I binded the remote obj
  4. Class Client as follow:

    import java.rmi.*;
    
    public class Client 
     {
         public static void main(String[] args) 
        { 
             try
            {
            String globalName = "rmi//127.0.0.1:1099/hello";
            RemoteInterface remoteObj = (RemoteInterface)Naming.lookup(globalName);
    
            System.out.println(remoteObj.SayHello());
    
    
            }
            catch(Exception e)
            {
                System.out.println(e.getMessage());
            }
    

I don't understand the reason why I must ude the interface RemoteInterface to do the lookup? Can't I use the HelloStub class, which is the real remote obj?

Thanks bye.


Solution

  • If you know the class name, you can define Stub class instance instead of RemoteInterface and cast your lookup result to your stub.

    But what benefit you will get defining stub insteadof Interface?