transient 关键字详解
一transient 作用
1、作用:将不需要序列化的属性 添加关键字 transient, 序列化对象的时候,这个属性就不会被序列化到指定目录中, 像银行卡、密码等等这些数据。
2、 序列化的对象包含被 transient 修饰的实例变量时,java 虚拟机(JVM)跳过该特定的变量。
该修饰符包含在定义变量的语句中,用来预处理类和变量的数据类型
二级目录
package com.zenlayer.javabasis.test;
import lombok.Data;
import java.io.*;
/**
* @author haoxiansheng
* @data 2020/5/1
*/
public class TestTransient {
/**
* 为了代码简洁直接抛出异常 实际场景应该捕获处理
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException, ClassNotFoundException {
//文件路径
String path = "/Users/haojunhu/Downloads/Spring-Family/springdata/application/src/main/java/com/zenlayer/javabasis/test/temp";
Customer customer = new Customer();
customer.setPassword("123456");
customer.setSex("男");
serizlizaCustomer(customer, path);
File file = new File(path);
deSerializeCustomer(file);
}
/**
* 序列化
*/
private static void serizlizaCustomer(Customer customer, String path) throws IOException {
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(path));
output.writeObject(customer);
output.close();
}
/**
* 反序列化
*/
private static void deSerializeCustomer(File file) throws IOException, ClassNotFoundException {
ObjectInputStream input = new ObjectInputStream(new FileInputStream(file));
Customer customer = (Customer) input.readObject();
System.out.println("输出 添加了transient 关键字序列化之后 " + customer.toString());
}
}
/**
* 实现序列化的两种方式
* 1、实现Serializable 接口
* 2、实现Exterranlizable 接口
*/
@Data
class Customer implements Serializable {
private transient static String name;
private transient String password;
private static Integer age;
private String sex;
public static void setName(String name) {
Customer.name = name;
}
public void setPassword(String password) {
this.password = password;
}
public static void setAge(Integer age) {
Customer.age = age;
}
/**
* 这个被static 修饰的属性没有toString 是添加不上的
* @return
*/
@Override
public String toString() {
return "Customer{" +
"password='" + password + '\'' +
", sex='" + sex + '\'' +
'}';
}
}
三有关问题
(1)transient底层实现的原理是什么?
java的serialization提供了一个非常棒的存储对象状态的机制,serialization就是把对象的状态存储到硬盘上去,需要的时候就可以再把它读出来使用。
有些时候像银行卡号这些字段是不希望在网络上传输的,transient的作用就是把这个字段的生命周期仅存于调用者的内存中而不会写到磁盘里持久化,意思是 transient修饰的字段,他的生命周期仅仅在内存中,不会被写到磁盘中。
(2)被transient关键字修饰过得变量真的不能被序列化嘛?
不能。
(3)静态变量能被序列化吗?被transient关键字修饰之后呢?
静态变量不管是不是transient 关键字修饰,都不会被序列化。