Deserialize remote object to the narrowest accessible class

独自空忆成欢 提交于 2019-12-04 02:21:59

问题


In shared.jar I have:

abstract class MyParent {

}
abstract class MyClass {
   MyParent getFoo();
}

server.jar contains

abstract class MyChild extends MyParent {

}
abstract class MyClassConcrete {
   MyParent getFoo() {return new MyChild();}
}

client.jar:

MyParent foo = myClass.getFoo();

If all 3 jars are in one classloader everything works well.

But client and server are in different JVMs while:

  • JVM-1 contains: server.jar, shared.jar
  • JVM-2 contains: client.jar, shared.jar

Client makes call to server. Server returns MyConcreteClass and Java fails to deserialize it (ClassNotFoundException).


What I wanna do:

  • Server serializes class and sends data and set of class's ancestors
  • Client finds the narrowest ancestor it may deserialize.

And everything is ok: we have instance of MyParent on the client and that is what we need.

I can't believe there is no such engines. Do you know one? I am sure remote call should be as similar to local calls as possible.

Thanks.


回答1:


Actually I found solution and made a special package to support it:

  • MyParent has to me marked with special SerializableParent annotation. This annotation means any child class should be "converted" to MyParent before remoting engine may serialize it and transfer it over the wire. By setting this annotation not only you tell the system MyParent exists on remote JVM but also hierarchy tree does not require polymorphism: if child overrides parent's method it would not be available on remote system because only data but code could be sent.
  • Before sending result engine should find narrowest ancestor annotated as SerializableParent
  • Object that should be serialized to XML (with XStream for example) and deserialized back using parent class as alias for child. To prevent "unknown fields" error Xstream has to be hacked by overriding wrapMapper and shouldSerializeMember.
  • You got "serializable parent" to be transfered



回答2:


An object implementing the java.io.Serializable interface can use the writeReplace() and readResolve() methods to substitute another object for the one being serialized/deserialized. I can see this being used to address your problem. However, I have not tried this myself.



来源:https://stackoverflow.com/questions/10249569/deserialize-remote-object-to-the-narrowest-accessible-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!