当没有指定默认构造函数时,java序列化如何反序列化最终字段? [英] How does java serialization deserialize final fields when no default constructor specified?

查看:627
本文介绍了当没有指定默认构造函数时,java序列化如何反序列化最终字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个定义不可变值类型的类,我现在需要序列化。不变性来自构造函数中设置的最终字段。我已经尝试过序列化了,但它确实有效(令人惊讶的是?) - 但我不知道怎么做。

I have an class defining an immutable value type that I now need to serialize. The immutability comes from the final fields which are set in the constructor. I've tried serializing, and it works (surprisingly?) - but I've no idea how.

这是一个类的例子

public class MyValueType implements Serializable
{
    private final int value;

    private transient int derivedValue;

    public MyValueType(int value)
    {
        this.value = value;
        this.derivedValue = derivedValue(value);
    }

    // getters etc...
}

鉴于该类没有没有arg构造函数,如何实例化并设置最终字段?

Given that the class doesn't have a no arg constructor, how can it be instantiated and the final field set?

(旁边 - 我注意到这个类特别是因为IDEA没有为这个类生成no serialVersionUID检查警告,但是成功地为其他类生成了警告'只是使序列化。)

(An aside - I noticed this class particularly because IDEA wasn't generating a "no serialVersionUID" inspection warning for this class, yet successfully generated warnings for other classes that I've just made serializable.)

推荐答案

反序列化由JVM在低于基本语言结构的级别上实现。具体来说,它不会调用任何构造函数。

Deserialization is implemented by the JVM on a level below the basic language constructs. Specifically, it does not call any constructor.

这篇关于当没有指定默认构造函数时,java序列化如何反序列化最终字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆