Serializable与transient

实现序列化必须实现Serializable接口,可以在类中实现writeObject和readObject控制序列化过程,具体可以参考ArrayList的实现.

transient标识可以在序列化时忽略该字段

public class User implements Serializable{
	
	private static final long serialVersionUID = 1L;
	private transient String name;
	private transient String password;
	private transient Integer age;
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("User [name=").append(name).append(", password=")
				.append(password).append(", age=").append(age).append("]");
		return builder.toString();
	}

	private void writeObject(java.io.ObjectOutputStream s)
    	throws java.io.IOException{
		s.writeUTF(name);
		s.writeUTF(password);
		s.writeInt(age);
	}
	
	private void readObject(java.io.ObjectInputStream s)
     	throws java.io.IOException, ClassNotFoundException {
		name = s.readUTF();
		password = s.readUTF();
		age = s.readInt();
	}
}



		User user = new User();
		user.setName("张三");
		user.setPassword("12345678");
		user.setAge(30);
		
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(bos);
		oos.writeObject(user);
		oos.flush();
		oos.close();
		
		byte[] value = bos.toByteArray();
		
		ByteArrayInputStream bis = new ByteArrayInputStream(value);
		ObjectInputStream ois = new ObjectInputStream(bis);
		user = (User) ois.readObject();
		ois.close();
		
		System.out.println(user);

结果为
User [name=张三, password=12345678, age=30]


其实在类里加writeObject和readObject方法和实现Externalizable没有什么区别

你可能感兴趣的:(java,idea)