Object serialize/ deserialize
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class TransientMember {
/**
* @param args
* @throws IOException
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws IOException, ClassNotFoundException {
// create new user with account & password
User user = new User();
user.account = "bruce";
user.password = "mypassword";
System.out.println(user);
// serialize
byte[] buffer = user.serialize();
// deserialize from byte array
User user2 = User.deserialize(buffer);
System.out.println(user2);
}
}
class User implements Serializable {
public String account;
transient public String password; // would not be serialize
@Override
public String toString() {
return String.format("<user account:%s password:%s>", this.account, this.password);
}
public byte[] serialize() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(this);
oos.close();
baos.close();
return baos.toByteArray();
}
public static User deserialize(byte[] buf) throws IOException, ClassNotFoundException {
ByteArrayInputStream bais = new ByteArrayInputStream(buf);
ObjectInputStream ois = new ObjectInputStream(bais);
Object o = ois.readObject();
ois.close();
bais.close();
return (User) o;
}
}