java.lang.ClassCastException: com.sun.proxy.$Proxy1 cannot be cast to

5k views Asked by At

Server:

Registry registry = LocateRegistry.createRegistry(1099);

InventoryInterface Inventory = new Inventory(registry);

registry.bind("Inventory", Inventory);

Client:

Registry registry = LocateRegistry.getRegistry(1099);


InventoryInterface inventory = (InventoryInterface) registry.lookup("Inventory");


String product_id = inventory.newProduct();

ProductFacade product_1 = (ProductFacade) registry.lookup(product_id);

The Problem is the exception happens at the casting, in this case it happens at: ProductFacade product_1 = (ProductFacade) registry.lookup(product_id);

Exception:

Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy2 cannot be cast to rmi.ProductFacade
2

There are 2 answers

8
Arty Jiang On

It can be about how you bind it. For example, if ProductFacade implements InventoryInterface you might need to cast it as InventoryInterface instead of ProductFacade.

2
user207421 On

Whatever is bound to the Registry under the name you're looking up does not implement the rmi.ProductFacade remote interface.

So I'm wondering if i should for example restart the Registry before casting again

Certainly not. (a) You can't restart it from the client, and (b) all you would get would be an empty Registry. The suggestion doesn't make sense.

Hard to see why InventoryInterface.newProduct() returns a String instead of the actual new ProductFacade object. Also why listAllProducts() returns a String rather than a String[]. I would redesign this without such heavy use of the Registry as follows:

public interface InventoryInterface extends Remote {    
    public ProductFacade newProduct() throws RemoteException;
    public ProductFacade getProduct(String id) throws RemoteException;    
    public String[] listAllProducts() throws RemoteException;
}