Sealed class objectInstance R8 null problem

259 views Asked by At

I have a selaed class that contains object like;

sealed class Item(val route:String,val showTopBar: Boolean = false) {
   object Example1: Item(route = "example1")
   object Example2: Item(route = "example2", showTopBar = true)
}

When I want to get object list from sealed class with reflection in release mode in my app;

val itemList = Item::class.nestedClasses.map {
   it.objectInstance as Item
}

it.objectInstance is null in release variant. This error is not existing in debug variant. How to solve this sealed class problem? Any proguard rule?

1

There are 1 answers

1
sgjesse On

To be able to reflect on classes you need to have keep rules on the classes you will be reflecting on. In this case Item and its subclasses. For the subclasses the instance field INSTANCE must also be kept.

The following rules with <packet> substituted appropriately should work:

-keepattributes InnerClasses,EnclosingMethod
-keep class <packet>.Item
-keep class * extends <packet>.Item {
  ** INSTANCE;
}

The -keepattributes is not strictly necessary if you are including the default rules provided by the Android Gradle plugin through getDefaultProguardFile("proguard-android-optimize.txt").