There is a workaround:
class Workaround extends ObjectInputStream {
String className;
public Workaround(InputStream in, Class<?> cls) throws IOException {
super(in);
this.className = cls.getName();
}
@Override
protected ObjectStreamClass readClassDescriptor() throws IOException,
ClassNotFoundException {
ObjectStreamClass cd = super.readClassDescriptor();
try {
Field f = cd.getClass().getDeclaredField("name");
f.setAccessible(true);
f.set(cd, className);
} catch (Exception e) {
throw new RuntimeException(e);
}
return cd;
}
}
Now I can write an instance of Test1 and read it as an instance of Test2
class Test1 implements Serializable {
private static final long serialVersionUID = 1L;
int i;
}
class Test2 implements Serializable {
private static final long serialVersionUID = 1L;
int i;
}
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("1"));
Test1 test1 = new Test1();
oos.writeObject(test1);
oos.close();
Workaround x = new Workaround(new FileInputStream("1"), Test2.class);
Test2 test2 = (Test2)x.readObject();