黑马程序员技术交流社区
标题:
序列化异常
[打印本页]
作者:
贾振凯
时间:
2013-4-3 23:41
标题:
序列化异常
本帖最后由 贾振凯 于 2013-4-16 21:39 编辑
public class Person implements Serializable{
private static final long serialVersionUID = 1L;
private static final Person p = new Person("jzk",1);;
private String name;
private int age;
private Person(String name, int age) {
this.name = name;
this.age = age;
}
public static Person getInstance(){
return p;
}
public String getName() {return name;}
public int getAge() { return age;}
private Object writeReplace()throws ObjectStreamException{
return new Dog("旺财"); //此处将序列化的对像用Dog来替换 }
private Object readResolve()throws ObjectStreamException{
return new Person("jkk",2); //此处读取的时候用new Person("jkk",2)来替换读取的对像值
}
}
public class SerializeOperate {
public static void main(String[] args){
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try {
oos = new ObjectOutputStream(new FileOutputStream("E:\\serialize.txt"));
ois = new ObjectInputStream(new FileInputStream("E:\\serialize.txt"));
oos.writeObject(Person.getInstance());
//根据上面的注释的理解,,,,,,,,,,,,这个地方为什么会报ClassCastException?????????????????////
System.out.println(Person.getInstance()==(Person)ois.readObject());
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("序列化异常!");
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("反序列化异常!");
}finally{
try {
if(oos != null)
oos.close();
}catch (IOException e) {
throw new RuntimeException("关闭列化流异常!");
}
try {
if(ois != null)
ois.close();
}catch (IOException e) {
throw new RuntimeException("关闭反序列化流异常!");
}
}
}
}
复制代码
作者:
黄玉昆
时间:
2013-4-15 12:55
你的这个代码有问题吧,其中的Dog是哪里来的啊,请写全代码,把问题写清楚,如果没问题了,请将问题分类改为“已解决”,谢谢
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2