JAVA序列化 Serializable 将对象转为数组,再反过来将数组转为对象

序列化过程中,其对象想要被序列化,那么它的类就要实现 此接口,这个对象的所有属性(包括private属性、包括其引用的对象)都可以被序列化和反序列化来保存、传递。


比如:在本实例中,DivSort必须实现Serializable接口,不实现的话,会在序列化过程中报错,一般会在o.writeObject(obj)的这一步骤报错。


import java.io.Serializable;

public class DivSort implements Serializable{
 public int age;
 public String name;
 public int score;
 
 
 
    public DivSort(int age, String name, int score) {
    super();
    this.age = age;
    this.name = name;
    this.score = score;
}
    public int getAge() {
    return age;
}
public void setAge(int age) {
    this.age = age;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public int getScore() {
    return score;
}
public void setScore(int score) {
    this.score = score;
}

}


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;


public class ArrayToByte{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // TODO Auto-generated method stub
        ArrayList<DivSort>  list1=new ArrayList<DivSort>();
        byte[] b=null;
        list1.add(new DivSort(12,"zhansan",234));
        list1.add(new DivSort(13,"zhansan",234));
        list1.add(new DivSort(14,"zhansan",234));
        for(DivSort l:list1) {
            System.out.println(l.age);
        }
        System.out.println("start");
        b=ArrayToByte.serialize(list1);
        System.out.println(b);
        System.out.println(ArrayToByte.deserialize(b));
        list1=(ArrayList<DivSort>) ArrayToByte.deserialize(b);
        for(DivSort d:list1) {
            System.out.println(d.getAge());
        }
        
    
        
    }
    
     public static byte[] serialize(Object obj) throws IOException {
            try(ByteArrayOutputStream b = new ByteArrayOutputStream()){
                try(ObjectOutputStream o = new ObjectOutputStream(b)){
                    o.writeObject(obj);
                }
                return b.toByteArray();
            }
        }

        public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
            try(ByteArrayInputStream b = new ByteArrayInputStream(bytes)){
                try(ObjectInputStream o = new ObjectInputStream(b)){
                    return o.readObject();
                }
            }
        }

    
    
    


}



上一篇:javadoc中的{@link }和{@linkplain }标签


下一篇:thinkphp-循环输出标签volist