Proguard rules for Sealed classes

1.2k Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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.

0
On

This was not working for me, maybe because my Sealed Class structure is much more complex? Problem was solved with using @Keep annotation at each level of Sealed Class inheritance, including the problematic Data Object at lowest level.