有一種變通方法:
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