zoukankan      html  css  js  c++  java
  • 自定义序列化

    package File;
    
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;
    import java.io.IOException;
    public class SerializeTest {
    	public static void main(String[] args) {
    		try (ObjectOutputStream oos = new ObjectOutputStream(
    				new FileOutputStream("transient.txt"));
    				ObjectInputStream ois = new ObjectInputStream(
    						new FileInputStream("transient.txt"))) {
    			Person per = new Person("孙悟空", 500);
    			oos.writeObject(per);
    			Person p = (Person) ois.readObject();
    			System.out.println(p.getName());//输出空悟孙
    			System.out.println(p.getAge());//输出501
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    class Person implements Serializable {           //序列化的类必须实现Serializable或Externalizable接口
    	private String name;
    	private transient int age;//transient表示不进行不序列化
    
    	public Person(String name, int age) {
    		this.name = name;
    		this.age = age;
    	}
    
    	public String getName() {
    		return this.name;
    	}
    
    	public int getAge() {
    		return this.age;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	public void setAge(int age) {
    		this.age = age;
    	}
    	
    	/*进行自定义序列化,要在序列化的类中添加两个方法,都是private,这里用到了反射*/
    	
    	private void writeObject(ObjectOutputStream out)throws IOException
    	{
    		out.writeObject(new StringBuffer(name).reverse());
    		out.writeInt(age);
    	}
    	private void readObject(ObjectInputStream in)throws IOException, ClassNotFoundException
    	{
    		this.name = ((StringBuffer)in.readObject()).toString();
    		this.age = in.readInt()+1;
    	}
    }
    
  • 相关阅读:
    c#将 1, 2, ..., 9共 9 个数字分成 3 组
    信息学院本科生创新项目总结
    Element-ui的使用
    fastmock接口管理
    mock安装与使用
    开闭原则
    里氏替换原则
    依赖倒置原则
    接口隔离原则
    单一职责原则
  • 原文地址:https://www.cnblogs.com/masterlibin/p/4788510.html
Copyright © 2011-2022 走看看