There is some legacy Java pojos which was used for binary serialization. Among the fields of one pojo, I have one enum field. Now in the new Java pojo, the enum field is replaced by a string field.
// old pojo with enum
class Test {
private DataType dataType;
private String someOtherField;
}
enum DataType {
Int,
Float,
String
}
// new pojo without enum field
class NewTest {
private String dataType;
private String someOtherField;
}
While reading(de-serializing) the old data, I have used the techniques mentioned here - https://stackoverflow.com/a/14608062/314310 to read old data into the new refactored pojo, which performs successfully for the non enum fields. But reading enum data to string field is almost seems impossible. I am getting exception as
java.lang.ClassCastException: cannot assign instance of demo.DataType to field demo.NewTest.dataType of type java.lang.String in instance of demo.NewTest
Is there anyway I can achieve this?
EDIT:
Here is the code for my custom ObjectInputStream
class MyObjectInputStream extends ObjectInputStream {
private static final Map<String, Class<?>> migrationMap = new HashMap<>();
static {
migrationMap.put("demo.Test", NewTest.class);
migrationMap.put("demo.DataType", String.class);
}
public MyObjectInputStream(InputStream stream) throws IOException {
super(stream);
}
@Override
protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException {
ObjectStreamClass resultClassDescriptor = super.readClassDescriptor();
for (final String oldName : migrationMap.keySet()) {
if (resultClassDescriptor != null && resultClassDescriptor.getName().equals(oldName)) {
Class<?> replacement = migrationMap.get(oldName);
try {
resultClassDescriptor = ObjectStreamClass.lookup(replacement);
} catch (Exception e) {
log.error("Error while replacing class name." + e.getMessage(), e);
}
}
}
return resultClassDescriptor;
}
}