序列化是将对象状态转换为可保持或传输的格式的过程,它也是RMI用来在不同JVM之间传递对象的机制,或者通过方法的参数或者作为一个方法调用的返回值。但有三个例外序列化不需要读或者写入到流:
1. 序列化会忽略静态字段,因为他们不属于对象的任何状态。
2. 基类的字段只有基类本身是序列化的时候才能被序列化。
3. 瞬间字段(transient)
我在写对象序列化时遇到了一点疑问,- import java.io.*;
- class Demo
- {
- public static void main(String[] args) throws Exception
- {
- //writeObj();
- readObj();
-
- }
-
- public static void writeObj() throws IOException
- {
- ObjectOutputStream oos =
- new ObjectOutputStream(new FileOutputStream("obj.txt"));
-
- Person p = new Person("zhangsan",22,"kr");
-
- oos.writeObject(p);
- oos.close();
-
- }
-
-
- public static void readObj() throws Exception
- {
- ObjectInputStream ois =
- new ObjectInputStream(new FileInputStream("obj.txt"));
-
- //如果Person类在存储后发生了变化 再去依据变化后的类去读取以前的会发生异常
- /*
- Exception in thread "main" java.io.InvalidClassException: Person; local class in
- compatible: stream classdesc serialVersionUID = 4485381321937480966, local class
- serialVersionUID = 4491012183083119912
- */
- Person p = (Person)(ois.readObject());
-
- sop(p.toString());
-
- }
-
-
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- }
复制代码- person.java
-
- import java.io.*;
-
- class Person implements Serializable
- {
- private String name;
- private transient int age;
- static String country = "cn";
- Person(String name,int age,String country)
- {
- this.name = name;
- this.age = age;
- this.country = country;
- }
-
- public String toString()
- {
- return name+":"+age+":"+country;
- }
-
- }
复制代码 我发现当我分别在main中read()和write()时得到了我想要的结果(前者)
当我在main中同时使用read()和wirte()时 发现静态变量居然变了. |
|