有一种变通方法:
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;
}
}
现在我可以写的Test1的实例,并把它读作的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();
谢谢你告诉我这个信息,但我需要解决的问题。 你能告诉我如何在周围?非常感谢你。 – user3081347
我已经告诉过你如何解决这个问题。改回它。 – EJP