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读出来