csqqer 发表于 2013-1-15 03:11:14

一个奇怪的Java序列化问题

import java.io.*;public class Customer implements Serializable {private int age;public Customer(int age ){this.age = age;}/* 第一处注释private void writeObject(ObjectOutputStream os)throws IOException{os.defaultWriteObject();System.out.println("write Object");}private void readObject(ObjectInputStream is)throws IOException,ClassNotFoundException{is.defaultReadObject();System.out.println("readObject ");} */public String toString(){return "age="+age;}public static void main(String[] args)throws Exception{Customer custormer = new Customer(24);System.out.println("before Serializable: "+custormer);ByteArrayOutputStream buf = new ByteArrayOutputStream();ObjectOutputStream o = new ObjectOutputStream(buf);o.writeObject(custormer);byte[] byteArray = buf.toByteArray();for(int i=0;i<byteArray.length;i++){System.out.print(byteArray+"");if((i%10==0 &&i!=0)|| i==byteArray.length-1)System.out.println();}//第二处注释byteArray=-1;byteArray=-1;byteArray=-1;byteArray=-10;ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(byteArray));custormer = (Customer)in.readObject();System.out.println("After Serializable:"+custormer);}}

1.上面的程序能正确运行,但加上第一处注释的内容后,运行时就会抛出Exception in thread "main" java.io.StreamCorruptedException: invalid type code: F6 异常,
2.对于第二处注释修改序列化对象的值有点不明白,为啥如上面的程序所示把最后 的四个字节设成-1 ,-1 -1 ,-10   结果就变成-10????
页: [1]
查看完整版本: 一个奇怪的Java序列化问题