关键字之transient

Java当中的transient  要解释这个关键字 需要先了解什么是Serializable序列化

一个类在实现了Serializable接口之后,这个类是可以被序列化的,但是有些属性不想将其序列化时 我们就可以用到  transient 关键字来修饰该属性, 这样就会在序列化的时候忽略该属性

import java.io.Serializable;

//这是一个简单的序列化类

//其中Password属性被赋予了transient修饰符
public class User implements Serializable{
    
    private String username;
    transient private String password;
    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 User(String username,String password){}//构造器省略....

public User(){}

public class test{

     public static void main(String arg[]) {

         User user=new User("陈","pa");

          testSerializable(user);//将其序列化

扫描二维码关注公众号,回复: 5091362 查看本文章

       User u=  unSerializable();//反序列化

      System.out.println(u.getUsername());

      System.out.println(u.getPassword());

     }

     public static void testSerializable(User u) throws FileNotFoundException, IOException{
        ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(new File("C://user.txt")));
        oos.writeObject(pay);
        oos.flush();
        oos.close();

     }

public static User  unSerializable() throws FileNotFoundException, IOException, ClassNotFoundException{
        ObjectInputStream ois=new ObjectInputStream(new FileInputStream(new File("C://payroll.txt")));
        Payroll pay=(Payroll) ois.readObject();
        return pay;
    }

}

输出:陈   null

我们可以看到当反序列化之时,是获取不到password属性的,说明 程序在序列化User类的时候忽略了该属性

拓展:

1.被static修饰的属性也是不能被序列化 的, 在反序列化时输出的是jvm里的数据,而不是被序列化后的数据

2.就算被transient修饰的属性也是可以被序列化的  因为序列化不只有Serializable  还可以用Externalizable来实现序列化,若实现的是Externalizable接口,在序列化的过程中需要在writeExternal方法中进行手工指定所要序列化的变量,这与是否被transient修饰无关。因此输出的是变量初始化的内容,而不是null。

还是给个例子吧....


public class User implements Externalizable{//实现externalizble接口
    
    private transient String a="我会被序列化吗?";

    public  void readExternal(ObjectInput in) throws IOException,
            ClassNotFoundException {
         a=(String) in.readObject();//在这里接收序列化的信息
    }

    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeObject(a);//在这个位置指定需要序列化的变量
    }
    
    public static void main(String[] args) {
        User user=new User();
        try {
            ObjectOutput  out=new ObjectOutputStream(new FileOutputStream(new File("test")));
            out.writeObject(user);
            
            ObjectInput in=new ObjectInputStream(new FileInputStream(new File("test")));
            user=(User) in.readObject();
            System.out.println(user.a);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

 输出:"我会被序列化吗?"

显而易见序列化成功! 

猜你喜欢

转载自blog.csdn.net/qq_36117744/article/details/86527224