How to generate serialVersionUID for kotlin exceptions?

后端 未结 3 1038
一个人的身影
一个人的身影 2021-02-06 04:28

As kotlin doesn\'t have static fields, should I define serialVersionUID in companion object?

3条回答
  •  清歌不尽
    2021-02-06 04:53

    To create the serialVersionUID for a class in Kotlin you have a few options all involving adding a member to the companion object of the class.

    The most concise bytecode comes from a private const val which will become a private static variable on the containing class, in this case MySpecialCase:

    class MySpecialCase : Serializable {
        companion object {
            private const val serialVersionUID: Long = 123
        }
    }
    

    You can also use these forms, each with a side effect of having getter/setter methods which are not necessary for serialization...

    class MySpecialCase : Serializable {
        companion object {
            private val serialVersionUID: Long = 123
        }
    }
    

    This creates the static field but also creates a getter as well getSerialVersionUID on the companion object which is unnecessary.

    class MySpecialCase : Serializable {
        companion object {
            @JvmStatic private val serialVersionUID: Long = 123
        }
    }  
    

    This creates the static field but also creates a static getter as well getSerialVersionUID on the containing class MySpecialCase which is unnecessary.

    But all work as a method of adding the serialVersionUID to a Serializable class.

提交回复
热议问题