Why use the `transient` keyword in java?
And a short use - case:
Imagine exposing a User - Object via a public available webservice.
You sure would like to expose things as nickname, online - state, maybe email or location.
You definitly would not want to expose the password the user uses to login.
Whilst this password could be a property of your User- object,
it should not be serialized e.g. when serializing the object to a JSON - String for the webservice mentioned.
transient variables are never serialized in java.
It marks a member variable not to be serialized when it is persisted to streams of bytes. When an object is transferred through the network, the object needs to be 'serialized'. Serialization converts the object state to serial bytes. Those bytes are sent over the network and the object is recreated from those bytes. Member variables marked by the java transient keyword are not transferred, they are lost intentionally.
please have a look at what serialization is.? and also refer this
Example
public class Foo implements Serializable
{
private String saveMe;
private transient String dontSaveMe;
private transient String password;
//...
}
In above example dontSaveMe
& password
are never get serialize as they are declare as a transient variables
.
transient
keyword suggests that the object should not be serialized, nor persisted. You can use it if you don't want to serialize heavy objects (such as Wrapper
s, for example, which can contain a lot of business logic).
@Transient
annotation suggests that the object should not be persisted (if you've been playing with Hibernate, for example), but it can be serialized.
I've included the annotation explanation, because I remember being confused by the two. :-)
transient
is used to specify which properties of an object will not be saved or serialised. For example, when saving an object to a file, transient
specifies which properties or attributes will not be saved to that file when that object is saved to a file.
When the object is re-created from the file, the value of that transient
attribute (or private property) will not be re-created as it was never saved, or serialised to that file. In some cases, you may want to avoid persisting some of these private instance variables or attributes of an object, transient
allows you to do that.