Sobes.tech
Junior

Co znamená klíčové slovo transient v Java?

sobes.tech AI

Odpověď od AI

Používá se u polí tříd a označuje, že toto pole by nemělo být serializováno během standardní serializace Java (použitím java.io.Serializable).

import java.io.Serializable;

public class User implements Serializable {
    private String username;
    private transient String password; // Toto pole nebude serializováno
    private int age;

    // Konstruktor, gettery a settery
    public User(String username, String password, int age) {
        this.username = username;
        this.password = password;
        this.age = age;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public int getAge() {
        return age;
    }
}

Při deserializaci budou pole transient inicializována výchozími hodnotami pro jejich typ (0 pro číselné primitivní typy, false pro boolean, null pro referenční typy).