zoukankan      html  css  js  c++  java
  • 【java】对象序列化Serializable、transient

     1 package 对象序列化;
     2 
     3 import java.io.Serializable;
     4 
     5 @SuppressWarnings("serial")
     6 class A implements Serializable{
     7     
     8 }
     9 public class TestSerializable {
    10     public static void main(String[] args) {
    11         
    12     }
    13 }
    View Code

     对象序列化:java.io.ObjectOutputStream

    对象反序列化:java.io.ObjectInputStream

     1 package 对象序列化;
     2 
     3 import java.io.File;
     4 import java.io.FileInputStream;
     5 import java.io.FileNotFoundException;
     6 import java.io.FileOutputStream;
     7 import java.io.IOException;
     8 import java.io.ObjectInputStream;
     9 import java.io.ObjectOutputStream;
    10 import java.io.Serializable;
    11 
    12 @SuppressWarnings("serial")
    13 class A implements Serializable{
    14     private String name;
    15     private transient int age;//transient修饰的成员不能被序列化
    16     public A(String name,int age){
    17         this.name=name;
    18         this.age=age;
    19     }
    20     @Override
    21     public String toString() {
    22         return "name="+name+",age="+age;
    23     }
    24 }
    25 public class TestSerializable {
    26     public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
    27         ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(new File("D:"+File.separator+"A.ser")));
    28         oos.writeObject(new A("张三",23));
    29         oos.close();
    30         
    31         ObjectInputStream ois=new ObjectInputStream(new FileInputStream(new File("D:"+File.separator+"A.ser")));
    32         A a=(A)ois.readObject();
    33         ois.close();
    34         System.out.println(a);
    35     }
    36 }
    Serializable和transient应用示例
  • 相关阅读:
    SpringBoot入门1
    git
    Linux 常用命令
    Linux虚拟机上安装redis
    用户登录(Material Design + Data-Binding + MVP架构模式)实现
    【方法总结】创建、读取、删除文件相关操作
    从源码角度入手实现RecyclerView的Item点击事件
    App启动页倒计时功能
    App内切换语言
    GreenDao与ReactiveX的完美搭配
  • 原文地址:https://www.cnblogs.com/xiongjiawei/p/6685924.html
Copyright © 2011-2022 走看看