简体   繁体   English

Java - 重命名枚举常量

[英]Java - Renaming Enum constants

I'm trying to make it so I can edit enum constants' names. 我正在努力使它能够编辑枚举常量的名称。

I have these classes: 我有这些课程:

public class MasterClass implements Serializable {


/**
 * 
 */
private static final long serialVersionUID = -7117733089486585811L;
private Sex sex;

public Sex getSex(){
    return sex;
}


}

.

public class Sex implements Serializable {

/**
 * 
 */
private static final long serialVersionUID = -4688254148082455942L;


private EnumModel model;

public String print(){
    return model.name();
}

public static String print(String n){
    return EnumModel.byName(n).name();
}

private static enum EnumModel {

    MALE_1(1, 2, 3),

    MALE_2(1, 2, 3),

    FEMALE_1(1, 2, 3),

    FEMALE_2(1, 2, 3)

    ;
    private int x, y, z;
    EnumModel(int...is){
        x = is[0];
        y = is[1];
        z = is[2];
    }

    public static EnumModel byName(String n){
        for (EnumModel a : EnumModel.values()){
            if (n.toLowerCase().replaceAll(" ", "_").equalsIgnoreCase(a.name().toLowerCase()))
                return a;

        }
        return null;
    }
}

}

Then after when I edit the name of the enum constant, for example, if I were to rename MALE_1 to MALE_ONE, then I will get this error: 然后,当我编辑枚举常量的名称后,例如,如果我要将MALE_1重命名为MALE_ONE,那么我将收到此错误:

Caused by: java.lang.IllegalArgumentException: No enum constant com.masterclass.sex.Sex.EnumModel.MALE_1
at java.lang.Enum.valueOf(Enum.java:238)
at java.io.ObjectInputStream.readEnum(ObjectInputStream.java:1750)

Because MALE_1 obviously no longer exists, the only way I can fix this is to delete the saved MasterClass and creating a new one. 因为MALE_1显然不再存在,我解决这个问题的唯一方法是删除已保存的MasterClass并创建一个新的MasterClass。

How do I re-name constants without this issue? 如何在没有此问题的情况下重命名常量?

Update serialVersionUid of the Sex class when you change it and write a custom deserializer (readObject) which checks versions and deserializes as appropriate. 更改Sex类的serialVersionUid并编写自定义反序列化器(readObject),它会根据需要检查版本和反序列化。 See http://www.oracle.com/technetwork/articles/java/javaserial-1536170.html 请参阅http://www.oracle.com/technetwork/articles/java/javaserial-1536170.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM