wuqi1040715350
wuqi1040715350
采纳率0%
2016-06-16 08:00 阅读 1.2k

序列化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条回答 默认 最新

  • w172087242 little_how 2016-06-16 08:03

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

    如果有帮助,希望采纳

    点赞 1 评论 复制链接分享
  • havedream_one havedream_one 2016-06-16 08:29
    点赞 评论 复制链接分享

相关推荐