How to generate a serialVersionUID in IntelliJ IDEA
Ever since the appearance of Jackson, GSON, and others, Java serialization has lost popularity. Many of these libraries don't even require that your classes implement the Serializable
interface. However, it's still a good idea to implement this interface in your Model classes. Frameworks such as Apache Wicket still require it.
Providing a serialVersionUID
field is not strictly required, but is highly recommended to declare it when implementing the Serializable
interface (Java Serialization). This field is used to enforce compatibility checks when deserializing a serialized object and verify that the object is compatible with the loaded class.
IntelliJ can generate this field for us whenever a class implements the Serializable
interface.
How to generate the serialVersionUID field with an IntelliJ plugin?
IntelliJ's marketplace offers a few plugins that implement this feature. I'm using the GenerateSerialVersionUID, which was the only one available when I needed this feature a few years ago. However, there are plenty of alternatives now.
Once you've enabled this plugin, you just need to press Alt+Insert
/Command+n
when you are in the body of a class implementing the Serializable
interface. You should see an option to generate the serialVersionUID
field for you.
How to generate serialVersionUID with IntelliJ's built-in features?
If you don't want to install any plugin, IntelliJ has some built-in features that you can enable and use to generate the serialVersionUID
field. There is a Serializable
inspection that has a quick-fix intention that we can take advantage of.
The first step is to enable the inspection in the settings dialog. Open Settings dialog (Ctrl+Alt+S
) and navigate to the Editor | Inspections tab.
With the inspection enabled, a warning is displayed whenever a Serializable
class doesn't declare a serialVersionUID
field. IntelliJ can now generate the field if you place the cursor on top of the warning. You can then press Alt+Enter
and select the Add 'serialVersionUID' field
option.