是否可以以兼容的方式更改 Serializable class 的某些字段的类型?

Is it possible to change the type of some field of a Serializable class in a compatible way?

public class SerializableTest implements Serializable
{
    /** field <code>serialVersionUID</code> */
    private static final long serialVersionUID = 3214128409127377143L;

    private String month;

    private int someInt;

    public String getMonth()
    {
        return month;
    }

    public void setMonth(String month)
    {
        this.month = month;
    }

    public int getSomeInt()
    {
        return someInt;
    }

    public void setSomeInt(int someInt)
    {
        this.someInt = someInt;
    }
}

我有这个 Serializable class,其中有一个名为 month 的字符串字段,当前包含一组固定的常量值 - "Jan"、"Feb" 等...

我想重构 class 以使用枚举内容而不是字符串:

public enum Month
{
    JAN("Jan"),
    FEB("Feb");

    private final String value;

    Month(String value)
    {
        this.value = value;
    }

    public String value() {
        return value;
    }

    public static Month fromValue(String v) {
        for (Month c: Month.values()) {
            if (c.value.equals(v)) {
                return c;
            }
        }
        throw new IllegalArgumentException(v);
    }
}

有没有可能以兼容的方式做到这一点? 我怀疑我需要提供枚举月份的自定义可序列化形式,但我不确定该怎么做。

为了向后兼容,您不能更改类型,但可以添加新字段。并在反序列化后更新新字段。

迁移所有数据后,您只需删除旧字段。