How to generate serialVersionUID for kotlin exceptions?

后端 未结 3 1036
一个人的身影
一个人的身影 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

    Yes, you can declare it in the companion object. The doc says:

    Also, public properties defined in objects and companion objects, as well as top-level properties annotated with const, are turned into static fields in Java

    But that seems to be the case with private properties too:

    class MyException: Exception() {
        companion object {
            private val serialVersionUid: Long = 1
        }
    }
    

    javap -c -p com.ninja_squad.kotlindiscovery.MyException.class

    Compiled from "MyException.kt"
    public final class com.ninja_squad.kotlindiscovery.MyException extends java.lang.Exception {
      private static final long serialVersionUid;
    
      public static final com.ninja_squad.kotlindiscovery.MyException$Companion Companion;
    
      static {};
        Code:
           0: getstatic     #38                 // Field com/ninja_squad/kotlindiscovery/MyException$Companion.INSTANCE:Lcom/ninja_squad/kotlindiscovery/MyException$Companion;
           3: putstatic     #40                 // Field Companion:Lcom/ninja_squad/kotlindiscovery/MyException$Companion;
           6: lconst_1      
           7: putstatic     #21                 // Field serialVersionUid:J
          10: return        
    
      public com.ninja_squad.kotlindiscovery.MyException();
        Code:
           0: aload_0       
           1: invokespecial #15                 // Method java/lang/Exception."":()V
           4: return        
    
      public static final long access$getSerialVersionUid$cp();
        Code:
           0: getstatic     #21                 // Field serialVersionUid:J
           3: lreturn       
    }
    

提交回复
热议问题