androidkotlinproguardsealed-classandroid-obfuscation

Proguard rules for Sealed classes


I have a sealed class as below.

    sealed class Fruits(private val category: String) {
      object Apple : Fruits("APPLE")
      class Banana : Fruits("BANANA)
    }

It gets obfuscated when minifyEnabled is true and debuggable is enabled like below:

public static abstract class Fruits {
   private Fruits(String param1String) {
      this.category = param1String;
   }
   
   public static final class Banana extends Fruits {
    static {
    
     }
   }
   
   public static final class Apple extends Fruits {
     public static final Apple INSTANCE = new Apple();
    
       private Apple() {
         super("APPLE", null);
       }
    }
 }

Do we have any proguard property which can prevent constructer removal for Banana class?


Solution

  • You can use the -keepclassmembers from the ProGuard rule to prevent constructor removal for the Banana class. It preserves specific class members, such as constructors, methods, and fields, during code obfuscation:

    -keepclassmembers class com.yourpackage.Fruits$Banana {
        <init>(...);
    }
    

    In this example, com.yourpackage should be replaced with the actual package name of your application.

    The <init>(...) part of the rule tells ProGuard to preserve the constructor of the Banana class along with its parameters.

    With this rule, the constructor of the Banana class will not be removed during code obfuscation, and you should be able to use it without any issues.