Java Reference
In-Depth Information
such as a
String
, that data will get serialized properly. In other words,
writeObject
works
recursively
. And carefully: if an object is referenced multiple times, it will only be serial-
izeed once. So, we can give it a
List
of
MyData
objects.
To be serializable, the data class must implement the empty
Serializable
interface. Also,
the keyword
transient
can be used for any data that should
not
be serialized. You might
need to do this for security or to prevent attempts to serialize a reference to an object of a
nonserializable class.
That said, making a class
Serializable
is not a decision that should be taken lightly. Con-
sideration should be given to enforcing class invariants during serialization, writing defens-
ive
readObject
or
readResolve
methods, initializing transient variables, etc.
Here
transient
is used to prevent unencrypted passwords from being saved where they
might be readable:
src/main/java/io/MyData.java
/** Simple data class used in Serialization demos. */
public
public class
class
MyData
MyData
implements
implements
Serializable
{
private
private static
static final
final
long
long
serialVersionUID
= -
4965296908339881739L
;
String userName
;
String passwordCypher
;
transient
transient
String passwordClear
;
/** This constructor is required by most APIs */
public
public
MyData
() {
// Nothing to do
}
public
public
MyData
(
String name
,
String clear
) {
setUserName
(
name
);
setPassword
(
clear
);
}
public
public
String
getUserName
() {
return
return
userName
;
}
public
public
void
void
setUserName
(
String s
) {
this
this
.
userName
=
s
;
}