Reputation: 95
I am trying to learn serialization and where I am not able to understand the below concept.
I have a class called Account and the class needs to be serialized, Accounts Class has two variables username and password. Of which password need not be serialized. So we are adding the keyword transient.
public class CustomizedSerialization{
public static void main(String[] args) throws IOException{
Account acc= new Account();
System.out.println("Serialization Started");
FileOutputStream fos= new FileOutputStream("userDetail.txt");
ObjectOutputStream oos= new ObjectOutputStream(fos);
oos.writeObject(acc);
System.out.println("Serialization Ended");
}
}
class Account implements Serializable{
String username="myusername";
transient String password="mypassword";
}
Fine it runs as expected the output is
Account UserName myusername
Account Password null
The trouble starts here. They say if you want to serialize the password also then write a callback methods with following signatures in the class that needs to be serialized.
Now I add this following code in my Account class
private void writeObject(ObjectOutputStream os) throws Exception{
System.out.println("writeObject Callback");
os.defaultWriteObject();
os.writeObject(password);
}
private void readObject(ObjectInputStream ois) throws Exception{
ois.defaultReadObject();
System.out.println("ReadObject Callback");
this.password=(String)ois.readObject();
}
Cool it works the job done….
Account UserName myusernamedurga
Account Password mypassword
Now my question is, we can realize this in a very simple way like removing the transient keyword for password. I believe there is some reason behind this, Can anyone explain me.
Thanks.
Upvotes: 1
Views: 164
Reputation: 262504
If you declare your class to be Serializable
, Java will serialize all of its fields.
You can turn this off selectively for some fields by making those transient
.
You can forgo the default serialization mechanism by implementing the writeObject
and readObject
methods. If you do that, you have complete freedom over how you want the object serialized.
And finally, you can mix and match: Implement the two methods, but still have Java serialize the "easy fields". To do this, you call defaultWriteObject
from within your own implementation of writeObject
. This will serialize all fields that are not transient for you, so you only have to worry about the others.
Now my question is, we can realize this in a very simple way like removing the transient keyword for password.
Yes. If the default way of serialization offered by just declaring Serializable
is good enough for you, then you can just do that.
You only need to use transient
, writeObject
etc if you want to customize something (for example by not writing out the password at all, or writing it out in some encrypted fashion).
Upvotes: 3