干了这杯Java之transient关键字

看源码的时候,发现transient这个关键字,不甚理解,查找资料发现:不被序列化

疑问:

  • 静态变量是不是不被序列化?
public class User implements Serializable {

	private static final long serialVersionUID = 2877054094045568710L;

	private String username;

	private transient String password;

	private static int age;

	public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} public int getAge() {
return age;
} public void setAge(int age) {
User.age = age;
} public static void main(String[] args) {
User user = new User();
user.setUsername("imeng");
user.setPassword("123456");
user.setAge(22); try {
ObjectOutputStream os = new ObjectOutputStream(
new FileOutputStream("/Users/imeng/Desktop/user.txt"));
os.writeObject(user);
os.close();
} catch (IOException e) {
e.printStackTrace();
} //序列号后改变Static的值
user.setAge(100); ObjectInputStream oi;
try {
oi = new ObjectInputStream(new FileInputStream("/Users/imeng/Desktop/user.txt"));
User readUser = (User) oi.readObject();
System.out.println("username:" + readUser.getUsername());
System.out.println("transient关键字password:" + readUser.getPassword());
System.out.println("静态变量age:" + readUser.getAge());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
username:imeng
password:null
age:100

结论:

  • transient关键字可以阻止序列化
  • 序列号并不保存静态变量
上一篇:angular请求传递不了数据


下一篇:poi导出Excel报表多表头双层表头、合并单元格