Sorted out some Java architecture, interview materials (micro services, clusters, distributed, middleware, etc.), partners in need can pay attention to the public number [programmer internal point], no routine to get
More choice
- Reeling off nine distributed ID generation methods, the interviewer gets a little confused
- 30,000 words summary, the essence of Mysql optimization
- I was forced to learn JAVA crawlers in order not to copy and paste
- The technology department suddenly announced that all JAVA developers would have to know the interface automation testing framework
- Redis 5 kinds of data structure and the corresponding use scenario, plenary interview to bonus points
Writing in the front
Recently, a fan of a public account told me about his interview experience. A rookie who had just spent two years in Java had a video interview due to the pandemic, and the interviewer only asked one question: “Why should Java serialization implement Serializable interface?” As a result, he was momentarily speechless. To be honest, I was also a little confused when I heard this question. I was usually busy studying various middleware and high availability frameworks, but I really had to turn back to the basic knowledge of Java and found that I owed too much technical debt. So I reviewed the knowledge of Java serialization with everyone.
What is Java serialization?
Serialization: The serialization mechanism in Java can write an instance object information to a byte stream (only serialize the object’s property values, but not the serialization method). The serialized object can be used for network transmission, or persisted to a database or disk.
Deserialization: When an object is needed, an identical object is reconstructed using information from the byte stream.
Implementing the Java.io.Serializable interface is the easiest way to serialize a class in Java.
public class User implements Serializable {
private static final long serialVersionUID = 1L;
}Copy the code
There are no methods or fields in the Serializable interface. The interface is only used to identify Serializable semantics, that is, whether an object can be serialized.
package java.io; /** * @author unascribed * @see java.io.ObjectOutputStream * @see java.io.ObjectInputStream * @see java.io.ObjectOutput Externalizable * @since JDK1.1 */ public interface Serializable {}Copy the code
Let’s test this by writing an object message to disk:
Create a User object and implement the Serializable interface
@Data
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String age;
}Copy the code
Writes User object information to disk
@Slf4j public class serializeTest { public static void main(String[] args) throws Exception { User user = new User(); user.setName("fufu"); user.setAge("18"); serialize(user); Log.info ("Java result before serialization :{} ", user); User duser = deserialize(); Log.info (" Result of Java deserialization :{} ", duser); } /** * @author XZF * @description serialize * @date 2020/2/22 19:34 */ private static void serialize(User User) throws Exception { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("D:\\111.txt"))); oos.writeObject(user); oos.close(); } /** * @author XZF * @description deserialize * @date 2020/2/22 19:34 */ private static User deserialize() throws Exception { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("D:\\111.txt"))); return (User) ois.readObject(); }}Copy the code
User(name=fufu, age=18) User(name=fufu, age=18)Copy the code
WriteObject () can serialize objects of type String, Array, Enum, Serializable, otherwise NotSerializableException will be raised.
This explains why Java serialization must implement the Serializable interface.
/**
* Underlying writeObject/writeUnshared implementation.
*/
private void writeObject0(Object obj, boolean unshared)
throws IOException
{
boolean oldMode = bout.setBlockDataMode(false);
depth++;
try {
// 省略号。。。。。。。。。。
// remaining cases
if (obj instanceof String) {
writeString((String) obj, unshared);
} else if (cl.isArray()) {
writeArray(obj, desc, unshared);
} else if (obj instanceof Enum) {
writeEnum((Enum<?>) obj, desc, unshared);
} else if (obj instanceof Serializable) {
writeOrdinaryObject(obj, desc, unshared);
} else {
if (extendedDebugInfo) {
throw new NotSerializableException(
cl.getName() + "\n" + debugInfoStack.toString());
} else {
throw new NotSerializableException(cl.getName());
}
}
} finally {
depth--;
bout.setBlockDataMode(oldMode);
}
}Copy the code
Why shouldn’t String implement the Serializable interface? Serializable is already implemented internally, so we don’t need to display the implementation. Look at the source code
public final class String implements java.io.Serializable, Comparable<String>, CharSequence { /** The value is used for character storage. */ private final char value[]; /** Cache the hash code for the string */ private int hash; /** Use serialVersionUID from JDK 1.0.2 for interoperability */ private static final long serialVersionUID = -6849794470754667710L; . }Copy the code
Why display the value specifying serialVersionUID when you have implemented the Serializable interface?
If serialVersionUID is not displayed when serializing an object, Java will automatically generate a serialVersionUID based on the object properties during serialization, which will be stored or used for network transmission.
During deserialization, a new serialVersionUID is automatically generated according to the object attributes and compared with the serialVersionUID generated during deserialization. If two serialVersionUID are the same, deserialization succeeds; otherwise, an exception will be thrown.
When the serialVersionUID is displayed, The serialVersionUID generated by Java is the serialVersionUID we set when serializing and deserializing objects, thus ensuring the success of deserialization.
transient
When serializing an object, use the transient keyword to specify which attribute you want not to serialize
@Data
public class User implements Serializable {
private transient String name;
private String age;
}Copy the code
As you can see, the value of field name is not saved to disk. Once the variable is transient, it is no longer part of the object persistence and its contents cannot be accessed after serialization.
Java deserialization result :User(name=null, age=18)Copy the code
A static variable cannot be serialized, whether or not it is transient. Because static attributes belong to classes, not objects.
conclusion
Share a very small knowledge point, work no matter how busy also do not forget to review old knowledge oh!
So much for today, if this article is a little help to you, I hope you can get a thumbs up 👍 oh
Your approval is my motivation to write!
Sorted out some Java architecture, interview materials (micro services, clusters, distributed, middleware, etc.), partners in need can pay attention to the public number [programmer internal point], no routine to get