美文网首页
Java关键字transient

Java关键字transient

作者: 无尘粉笔 | 来源:发表于2021-03-16 09:10 被阅读0次

transient (英文直译)短暂的;转瞬即逝的;暂时的;

u=1496752728,2853013307&fm=26&gp=0.jpg

我们知道一个对象要实现我们都知道一个对象只要实现了Serilizable接口,这个对象就可以被序列化,java的这种序列化模式为开发者提供了很多便利,我们可以不必关系具体序列化的过程,只要这个类实现了Serilizable接口,这个类的所有属性和方法都会自动序列化。然而在实际开发过程中,我们常常会遇到这样的问题,这个类的有些属性需要序列化,而其他属性不需要被序列化,打个比方,如果一个用户有一些敏感信息(如密码,银行卡号等),为了安全起见,不希望在网络操作(主要涉及到序列化操作,本地序列化缓存也适用)中被传输,这些信息对应的变量就可以加上transient关键字。换句话说,这个字段的生命周期仅存于调用者的内存中而不会写到磁盘里持久化。

package com.wcfb.dto;

import lombok.Builder;
import lombok.Data;

import java.io.Serializable;

/**
 * @description:
 * @author: yz
 * @create: 2021-03-15 21:08
 **/
@Data
@Builder
public class UserDto implements Serializable {
    private static final long serialVersionUID = 3601470141407545994L;

    private String account;
    private transient String password;
    private String name;
}
package com.wcfb.service;

import com.wcfb.dto.UserDto;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * @description:
 * @author: yz
 * @create: 2021-03-15 21:02
 **/
@Slf4j
public class TransientTest {
    public static void main(String[] args) {
        ObjectOutputStream oos = null;
        UserDto userDto = UserDto.builder().account("123456").password("p123456").name("张三").build();
        try {
            oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("E:\\appData\\temp\\temp.txt")));
            oos.writeObject(userDto);
            log.info("保存对象前: {}", userDto.toString());
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream("ObjectData")));
            try {
                UserDto userDto1 = (UserDto) ois.readObject();
                log.info("保存对象后:{}", userDto1.toString());
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
image.png

相关文章

网友评论

      本文标题:Java关键字transient

      本文链接:https://www.haomeiwen.com/subject/dqjlcltx.html