Guide to the @Serial Annotation in Java 14 – Java 14中的@Serial注解指南

最后修改: 2020年 1月 6日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

In this quick tutorial, we’ll take a look at the new @Serial annotation introduced with Java 14.

在这个快速教程中,我们将看看Java 14引入的新@Serial注解。

Similarly to @Override, this annotation is used in combination with the serial lint flag to perform compile-time checks for the serialization-related members of a class.

@Override类似,该注解与序列化lint标志结合使用,以对类的序列化相关成员执行编译时检查。

Although the annotation is already available as per build 25, the lint check has yet to be released.

尽管按照build 25的规定,注释已经可用,但lint检查尚未发布。

2. Usage

2.使用方法

Let’s start by annotating with @Serial any of the seven serialization-related methods and fields:

让我们先用@Serial注释七个与序列化相关的方法和字段中的任何一个。

public class MySerialClass implements Serializable {

    @Serial
    private static final ObjectStreamField[] serialPersistentFields = null;
	
    @Serial
    private static final long serialVersionUID = 1;
	
    @Serial
    private void writeObject(ObjectOutputStream stream) throws IOException {
        // ...
    }
	
    @Serial
    private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
        // ...
    }

    @Serial
    private void readObjectNoData() throws ObjectStreamException {
        // ...
    }

    @Serial
    private Object writeReplace() throws ObjectStreamException {
        // ...
        return null;
    }

    @Serial
    private Object readResolve() throws ObjectStreamException {
        // ...
        return null;
    }

}

After that, we need to compile our class with the serial lint flag:

之后,我们需要用串行lint标志编译我们的类

javac -Xlint:serial MySerialClass.java

The compiler will then check the signatures and the types of the annotated members and issue a warning if they don’t match the expected ones.

然后编译器将检查被注释的成员的签名和类型,如果它们与预期的不一致,将发出警告。

Furthermore, the compiler will also throw an error if @Serial is applied:

此外,如果应用了@Serial,编译器也会抛出一个错误。

  • when a class is not implementing the Serializable interface:
public class MyNotSerialClass {
    @Serial 
    private static final long serialVersionUID = 1; // Compilation error
}
public enum MyEnum { 
    @Serial 
    private void readObjectNoData() throws ObjectStreamException {} // Compilation error 
}
  • to writeObject(), readObject(), readObjectNoData() and serialPersistentFields in an Externalizable class since those classes use different serialization methods:
public class MyExternalizableClass implements Externalizable {
    @Serial 
    private void writeObject(ObjectOutputStream stream) throws IOException {} // Compilation error 
}

3. Conclusion

3.结论

This short article went through the new @Serial annotation usage.

这篇短文介绍了新的@Serial注解用法。

As always, all the code in the article is available over on GitHub.

一如既往,文章中的所有代码都可以在GitHub上找到