wuqi1040715350 2016-06-16 08:00 采纳率: 0%
浏览 1206

序列化static变量问题

public class User implements Serializable {

private static final long serialVersionUID = 4403512922350207270L;
private String name;
private int age;
private Date birthday;
static int count = 1 ;
private transient String gender;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}

public Date getBirthday() {
    return birthday;
}

public void setBirthday(Date birthday) {
    this.birthday = birthday;
}

public String getGender() {
    return gender;
}

public void setGender(String gender) {
    this.gender = gender;
}


@Override
public String toString() {
    return "User{" +
            "name=" + name + ", age=" + age +
            ", gender=" + gender +
            ", birthday=" + birthday + ",count=" +count +
            '}';
}

}

测试序列化
public class Test {
public static void main(String[] args) {

    User user = new User();
    user.setName("hollis");
    user.setGender("male");
    user.setAge(23);
    user.setBirthday(new Date());
    System.out.println(user);

    //Write Obj to File
    ObjectOutputStream oos = null;
    try {
        oos = new ObjectOutputStream(new FileOutputStream("D:/tempFile.txt"));
        oos.writeObject(user);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(oos);
    }



}

}
输出内容为User{name=hollis, age=23, gender=male, birthday=Thu Jun 16 15:59:10 CST 2016,count=1}

测试反序列化
public class Test1 {
public static void main(String[] args) {
//Read Obj from File
File file = new File("D:/tempFile.txt");
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream(file));
User newUser = (User) ois.readObject();
System.out.println(newUser);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(ois);
try {
FileUtils.forceDelete(file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
输出内容为User{name=hollis, age=23, gender=null, birthday=Thu Jun 16 15:59:10 CST 2016,count=1}

不是说static变量不能被序列化吗,为什么反序列化的时候还能把count读出来

  • 写回答

2条回答 默认 最新

  • little_how 2016-06-16 08:03
    关注

    count确实没有序列化,但是你的类变量count初始化就是1,
    你可以在序列化之前,改变count的值,然后反序列化回来,你会发现,count还是1.
    这就证明了static类型变量是不会被序列化的。

    如果有帮助,希望采纳

    评论

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错