【问题标题】:Java serialization, Can I change the datatype of the variable?Java序列化,我可以更改变量的数据类型吗?
【发布时间】:2017-07-10 15:57:21
【问题描述】:

我需要在序列化和反序列化时更改quantity字段的数据类型。`

DoubleIntegerwriteObject();

Integer 中的Double readObject();

物品类

class Items implements Serializable {

    private static final long serialVersionUID = 1537402844776823455L;

    Double quantity;

    private void writeObject(ObjectOutputStream o) throws IOException {
        PutField field = o.putFields();
        field.put("quantity", quantity.intValue());
    }

    private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException {

        GetField field = stream.readFields();

        if((field.get("quantity", new Double(0)) instanceof Integer)){
            quantity = ((Integer) field.get("quantity", new Integer(0))).doubleValue();
        }else if((field.get("quantity", new Double(0)) instanceof Double)){
            quantity = (Double) field.get("quantity", new Double(0));
        }
    }
}

我试过这个,但反序列化时数量总是加倍。

quantity 字段在类中必须是 Double,在序列化对象中必须是 Integer。 这可以通过序列化实现吗?

【问题讨论】:

  • 为什么?您将失去精度和范围。
  • 服务器将接收两种类型的序列化对象,一种是数量字段 Double 另一种是 Integer,在服务器端需要反序列化请求并强制转换为 double。

标签: java serialization deserialization


【解决方案1】:

试试 java.lang.Number。 Integer 和 Double 扩展它。

【讨论】:

    猜你喜欢
    • 2015-09-09
    • 2015-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    • 2011-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多