什么是Java序列化和反序列化,如何实现Java序列化?或者请解释Serializable 接口的作用
https://blog.csdn.net/m0_37450089/article/details/78542825
public class mySerializeable implements Serializable { // final 修饰的成员变量可以 声明时赋值 或在构造块中赋值 或构造方法中赋值 private final String name; private final int age; // static final 修饰的变量 只能 声明时赋值和在静态块中赋值 private static final int gender; public mySerializeable(){ // name = ""; // age = 0; System.out.println("构造方法"); // name = ""; } { System.out.println("构造代码块2"); } { System.out.println("构造代码块1"); name = ""; age = 0; } static{ System.out.println("静态代码块"); // name = ""; // age = 10; gender = 0; } public void init(){ // name = ""; // age = 0; } @Override public String toString() { return "mySerializeable{" + "name='" + name + '\'' + ", age=" + age + '}'; } public static void main(String[] args){ mySerializeable m = new mySerializeable(); try{ //序列化到文件 ObjectOutputStream oos= new ObjectOutputStream(new FileOutputStream(new File("obj.txt"))); oos.writeObject(m); //从文件中反序列化 ObjectInputStream ois =new ObjectInputStream(new FileInputStream("obj.txt")); mySerializeable m2 =(mySerializeable) ois.readObject(); System.out.println(m2); // 字节数组 ByteArrayOutputStream bos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(bos); oos.writeObject(m); byte[] bytes = bos.toByteArray(); // 从字节数组中反序列化 ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ois = new ObjectInputStream(bis); m2 =(mySerializeable) ois.readObject(); System.out.println(m2); }catch (Exception e){ } } }