本帖最后由 贾振凯 于 2013-4-3 23:40 编辑
- 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("关闭反序列化流异常!");
- }
- }
- }
- }
复制代码 |
|