有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java序列化将枚举读取为字符串

有一些用于二进制序列化的遗留Java POJO。在一个pojo的字段中,我有一个枚举字段。现在在新的JavaPOJO中,枚举字段被字符串字段替换

// old pojo with enum
class Test {
    private DataType dataType;
    private String someOtherField;
}

enum DataType {
    Int,
    Float,
    String
}

// new pojo without enum field
class NewTest {
    private String dataType;
    private String someOtherField;
}

在读取(反序列化)旧数据时,我使用了这里提到的技术-https://stackoverflow.com/a/14608062/314310将旧数据读取到新的重构pojo中,该pojo成功地执行了非枚举字段。但将枚举数据读取到字符串字段几乎是不可能的。我也有例外

java。lang.ClassCastException:无法分配演示的实例。数据类型到字段演示。纽特。java类型的数据类型。演示实例中的lang.String。新测试

我有没有办法做到这一点

编辑:

这是我的自定义ObjectInputStream的代码

class MyObjectInputStream extends ObjectInputStream {
    private static final Map<String, Class<?>> migrationMap = new HashMap<>();

    static {
        migrationMap.put("demo.Test", NewTest.class);
        migrationMap.put("demo.DataType", String.class);
    }

    public MyObjectInputStream(InputStream stream) throws IOException {
        super(stream);
    }

    @Override
    protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException {
        ObjectStreamClass resultClassDescriptor = super.readClassDescriptor();

        for (final String oldName : migrationMap.keySet()) {
            if (resultClassDescriptor != null && resultClassDescriptor.getName().equals(oldName)) {
                Class<?> replacement = migrationMap.get(oldName);

                try {
                    resultClassDescriptor = ObjectStreamClass.lookup(replacement);
                } catch (Exception e) {
                    log.error("Error while replacing class name." + e.getMessage(), e);
                }
            }
        }

        return resultClassDescriptor;
    }
}

共 (1) 个答案

  1. # 1 楼答案

    尝试将您的枚举更改为:

    enum DataType {
        Int,
        Float,
        String;
    
        public static DataType getFromString(String stringDataType) {
            for(DataType dataType in DataType.values()) {
                if (dataType.toString().equals(stringDataType)) {
                    return dataType;
                }
             }
             throw new IllegalArgumentException("Invalid input");
        }
    }
    

    因此,当您要将枚举分配给您调用的字符串时:

    newTest.dataType = test.dataType.toString();
    

    当您想将字符串分配给Enum时,可以调用:

    test.dataType = DataType.getFromString(newTest.dataType);