Java

Java 中的 Serializable 与 transient

2016-07-17  本文已影响970人  萌面大道

由于种种原因,简书等第三方平台博客不再保证能够同步更新,欢迎移步 GitHub:https://github.com/kingcos/Perspective/。谢谢!

注:
由于目前个人对 Java 的理解应用仅限于皮毛,故若有不妥,望及时告知,会及时修正。

前言

Java 中的 transient 是有关对象序列化的关键字,之前学习中并没有注意,并且没有实际使用。但是这次希望可以总结一下,来了解 Java 的这个特点,故记录于此。

作用

序列化(Serializable)是指把 Java 对象字节序列的过程,就是说将原本保存在内存中的对象,保存到硬盘(或数据库等)中。当需要使用时,再反序列化恢复到内存中使用。在我查到的资料中,通过网络传递对象或是RMI(Remote Method Invocation远程方法调用)都会用到对象序列化。transient 译为短暂的,在这里即不被持久化。有一些敏感数据是不适合被传输,因此需要加上 transient 关键字,即可避免序列化。

Demo

实体类:Account.java

import java.io.Serializable;

// 参与序列化只需要实现 Serializable 接口即可
public class Account implements Serializable {
    // Java 的序列化机制通过判断以下 ID 来进行版本比对,本处使用默认
    private static final long serialVersionUID = 1L;
    
    private Long accountId;
    private String username;
    // transient 修饰:
    private transient String password;
    private transient double balance;
    
    public static int staticVar;
    
    public Account(Long accountId, String username, String password, double balance) {
        super();
        this.accountId = accountId;
        this.username = username;
        this.password = password;
        this.balance = balance;
    }

    public String toString() {
        return "Account [accountId=" + accountId + ", username=" + username + ", password=" + password + ", balance="
                + balance + "]";
    }
    
}

测试类:TestTransient.java

import java.io.*;

public class Demo01 {

    public static void main(String[] args) {
        // 此处需要改为你要存入的地址,注意 Win 下地址中的 \ 需要转义
        String src = "/Users/kingcos/Desktop/demo.object";
        Account kingcos = new Account(62278888L, "kingcos", "123456", 1000.0);
        Account.staticVar = 11;
        System.out.println("序列化之前:");
        System.out.println(kingcos);
        System.out.println("staticVar = " + Account.staticVar);
        
        write(kingcos, src);
        Account.staticVar = 22;
        Account newKingcos = read(src);
        System.out.println("序列化之后:");
        System.out.println(newKingcos);
        System.out.println("staticVar = " + Account.staticVar);
    }
    
    static void write(Account acc, String src) {
        OutputStream os = null;
        ObjectOutputStream oos = null;
        try {
            os = new FileOutputStream(src);
            oos = new ObjectOutputStream(os);
            // 写入
            oos.writeObject(acc);
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                oos.flush();
                oos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    static Account read(String src) {
        Account acc = null;
        InputStream is = null;
        ObjectInputStream ois = null;
        try {
            is = new FileInputStream(src);
            ois = new ObjectInputStream(is);
            // 读取
            acc = (Account) ois.readObject();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return acc;
    }
}

// Console:
// 序列化之前:
// Account [accountId=62278888, username=kingcos, password=123456, balance=1000.0]
// staticVar = 11
// 序列化之后:
// Account [accountId=62278888, username=kingcos, password=null, balance=0.0]

总结

序列化

serialVersionUID

静态变量

其它

Externalizable

Externalizable
Externalizable 接口内部实现了 Serializable 接口,但是为其扩展了两个方法,writerExternal() 方法在序列化时被自动调用,可以在其中控制序列化内容,readExternal() 方法在反序列化时被自动调用,可以在其中控制反序列化的内容。如果留空,(反)序列化行为将不会保存或读取任何一个字段,所以 transient 关键字也失效。因此我们可以对(反)序列化进行控制,详见下面的 Demo。
注意:
使用 Externalizable 进行序列化时,当读取对象时,会调用被序列化类的无参构造方法去创建一个新的对象,然后再将被保存对象的字段的值分别填充到新对象中。因此,实现 Externalizable 接口的类必须要提供一个无参的构造器,且它的访问权限为 public。

Demo

该 Demo 基于上处改编

实体类:Account.java

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

// Externalizable 接口内部也实现了 Serializable
public class Account implements Externalizable {
    // Java 的序列化机制通过判断以下 ID 来进行版本比对,本处使用默认
    private static final long serialVersionUID = 1L;
    
    private Long accountId;
    private String username;
    // transient 修饰:
    private transient String password;
    private transient double balance;
    
    public static int staticVar;
    
    public Account() {
        super();
        System.out.println("调用了 无参构造方法");
    }
    
    public Account(Long accountId, String username, String password, double balance) {
        super();
        this.accountId = accountId;
        this.username = username;
        this.password = password;
        this.balance = balance;
    }

    @Override
    public String toString() {
        return "Account [accountId=" + accountId + ", username=" + username + ", password=" + password + ", balance="
                + balance + "]";
    }

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        System.out.println("调用 writeExternal");
        out.writeLong(accountId);
        out.writeObject(password);
        out.writeDouble(balance);
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        System.out.println("调用 readExternal");
        accountId = in.readLong();
        // 对象类型需要强制类型转换
        password = (String) in.readObject();
        balance = in.readDouble();
    }
    
}

测试类:TextExternalizable.java

import java.io.*;

public class TextExternalizable {

    public static void main(String[] args) {
        // 此处需要改为你要存入的地址,注意 Win 下地址中的 \ 需要转义
        String src = "/Users/kingcos/Desktop/demo.object";
        Account kingcos = new Account(62278888L, "kingcos", "123456", 1000.0);
        Account.staticVar = 11;
        System.out.println("序列化之前:");
        System.out.println(kingcos);
        System.out.println("staticVar = " + Account.staticVar);
        
        write(kingcos, src);
        Account.staticVar = 22;
        Account newKingcos = read(src);
        System.out.println("序列化之后:");
        System.out.println(newKingcos);
        System.out.println("staticVar = " + Account.staticVar);
    }
    
    static void write(Account acc, String src) {
        OutputStream os = null;
        ObjectOutputStream oos = null;
        try {
            os = new FileOutputStream(src);
            oos = new ObjectOutputStream(os);
            // 写入
            oos.writeObject(acc);
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                oos.flush();
                oos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    static Account read(String src) {
        Account acc = null;
        InputStream is = null;
        ObjectInputStream ois = null;
        try {
            is = new FileInputStream(src);
            ois = new ObjectInputStream(is);
            // 读取
            acc = (Account) ois.readObject();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return acc;
    }
}

// Console:
// 序列化之前:
// Account [accountId=62278888, username=kingcos, password=123456, balance=1000.0]
// staticVar = 11
// 调用 writeExternal
// 调用了 无参构造方法
// 调用 readExternal
// 序列化之后:
// Account [accountId=62278888, username=null, password=123456, balance=1000.0]
// staticVar = 22

参考资料

本人博客:https://maimieng.com

上一篇 下一篇

猜你喜欢

热点阅读