java serialization and final fields
        Posted  
        
            by mdma
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by mdma
        
        
        
        Published on 2010-05-25T12:32:18Z
        Indexed on 
            2010/05/25
            12:41 UTC
        
        
        Read the original article
        Hit count: 401
        
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.
Here's an example of the class
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...
}
Given that the class doesn't have a no arg constructor, how can it be instantiated and the final field set?
(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.)
© Stack Overflow or respective owner