Java RMI ClassCast异常

时间:2017-03-23 03:25:22

标签: java rmi

我正在使用以下JAVA RMI设置开发分布式系统。

public interface NodeOperations {
 /* RMI methods */
 public FingerTable getFingerTable() throws RMIException;
}

public class Node implements NodeOperations {
 /* Implements all RMI methods */
 /* Also holds a object of FingerTable */
 FingerTable ft;

}

public class FingerTable {
 /* Holds a reference to Node class which has object of 'this' FingerTable */
 Node self;
}

所有RMI通信都是通过NodeOperations接口中的方法完成的。有一种方法可以为特定节点返回FingerTable个对象。但是,当我从客户端调用该方法时,我会遇到异常。我该如何解决这个问题?

java.lang.ClassCastException: cannot assign instance of com.sun.proxy.$Proxy5 to field chord.FingerTable.self of type chord.Node in instance of chord.FingerTable
    at java.io.ObjectStreamClass$FieldReflector.setObjFieldValues(ObjectStreamClass.java:2133)
    at java.io.ObjectStreamClass.setObjFieldValues(ObjectStreamClass.java:1305)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2237)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2155)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2013)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2231)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2155)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2013)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:422)
    at sun.rmi.server.UnicastRef.unmarshalValue(UnicastRef.java:326)
    at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:175)
    at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:227)
    at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:179)
    at com.sun.proxy.$Proxy5.getNodeInfo(Unknown Source)
    at chord.NodeTest.testTopology(NodeTest.java:108)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

1 个答案:

答案 0 :(得分:1)

  1. 如果Node打算成为远程对象:

    • NodeOperations应扩展Remote
    • Node应扩展UnicastRemoteObject或通过UnicastRemoteObject.exportObject()导出。
    • 应宣布
    • NodeOperations.getFingerTable()抛出RemoteException
    • 您不应该有Node类型的字段:它应该是NodeOperations类型。

    根据例外情况,Node 已经是导出的远程对象。所以这不是真正的代码。

  2. 否则,即如果您不希望Node成为远程对象,则Node应实现Serializable,声明serialVersionUID成员等。

  3. 您的班级定义似乎相当循环。检讨它们。