How to not allow serialization of attributes of a class in Java?

I am new to Java and am curious to know how to not allow the serialization of attributes of a class in Java.

Comments

  • Use the transient keyword. The transient keyword can be used to mark a field as transient, which means that it will not be serialized.
    For example:

    public class Person implements Serializable {

    private transient String name;
    
    public Person(String name) {
        this.name = name;
    }
    

    }

    In this example, the name field will not be serialized.

    Override the writeObject() and readObject() methods. The writeObject() and readObject() methods are called by the serialization runtime to serialize and deserialize an object. If you override these methods, you can prevent the serialization of specific attributes by throwing a NotSerializableException.
    For example:

    public class Person implements Serializable {

    private String name;
    
    public Person(String name) {
        this.name = name;
    }
    
    private void writeObject(ObjectOutputStream out) throws IOException {
        throw new NotSerializableException("The name field is not serializable");
    }
    
    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        throw new NotSerializableException("The name field is not serializable");
    }
    

    }

    In this example, the name field will not be serialized, even if the transient keyword is not used.

    Which method you use depends on your specific needs. If you only need to prevent the serialization of a few attributes, then using the transient keyword is the simpler option. However, if you need to prevent the serialization of all attributes, or if you need to do some custom serialization logic, then overriding the writeObject() and readObject() methods is the better option.

Leave a Comment

BoldItalicStrikethroughOrdered listUnordered list
Emoji
Attach file
Attach image
Align leftAlign centerAlign rightToggle HTML viewToggle full pageToggle lights
Drop image/file