简体   繁体   中英

Can I DeSerialize a java serialized object to different classes?

Unsure how to frame the question. Here is a try :

I have two aerospike caches (sets) say X, Y.

there are two versions of a jar each has a class com.xyz.MyClass

jar1 :

com.xyz.MyClass{
    com.abc.Request request;
    ...
}

jar2 :

com.xyz.MyClass{
    com.pqr.Request request;
    ...
}

Now Some objects of MyClass from jar1 are stored in cache X and some objects of MyClass from jar2 are stored in cache Y.

I want to deserialize data from both the caches, perform some computation and store in a db.

I can't serialize as the fully qualified name of MyClass in both jars is same.

I will remove one of the caches (but that will take some time). So, Hoping for a temporary fix to handle this situation for now.

Can i handle this in a nice way?

Maybe deserialize into something intermediary(that doesn't care about packages, but only class structure) and then to MyClass.

Note : both the classes have same structure, just package name of a member variable is different.

PS : Don't want to use multiple class loaders.

It will take huge amount of magic to achive it, and disallowing classloader magic remove half of your options.

Solution that I can propose is editing serialized data. Format in which object are serialized is known and is part of Java spec. So you can edit this bytes to replace one class name to another, but I suggest you think twice before you start to implement this. It may be not so trivial task.

Generate two different serialVersionUID's and use them in each of the class.

private static final long serialVersionUID = -7000188057019447678L;// Add this in MyClass of jar1

private static final long serialVersionUID = -3944128180162145709L;// Add this in MyClass of jar2

You can generate your own serialVersionUID's using Eclipse IDE or JDK's serialver tool .

Note : If no serialVersionUID is declared, JVM will use its own algorithm to generate a default SerialVersionUID. you can check the algorithm here.

The default serialVersionUID computation is highly sensitive to class details and may vary from different JVM implementation, and result in an unexpected InvalidClassExceptions during the deserialization process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM