lundi 3 août 2020

Kotlin reflection doesn't work when code obfuscation is enabled

I have this class

object Config {

    val type = Type
    val clazz = Class

    object Type {
        val type1 = "1"
        val type2 = "2"
        val type3 = "3"
    }

    object Class {
        val class1 = "1"
        val class2 = "2"
        val class3 = "3"
    }
}

I need to get all variables (type1, type2, type3, class1, class2, class3).

To do this I have this method:

fun getAll(instance: Any? = null, depth: Int = 0): List<String> {
        if (depth > 2) {
            return emptyList()
        }

        val result = mutableListOf<String>()
        val currentInstance = instance ?: this

        val properties = currentInstance.javaClass.kotlin.declaredMemberProperties.filter { it.visibility == KVisibility.PUBLIC }
        
        for (prop in properties) {
            prop.get(currentInstance)?.let {

                if (it is String) {
                    result.add(it)
                } else {
                    result.addAll(getAll(it, depth + 1))
                }
            }
        }

        return result
    }

It works fine if code obfuscation is disabled.

When I add:

minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'

It doesn't work anymore.

I tried to add @Keep annotation or a similar proguard rule. It doesn't work.

Important note. type1, type2, type3, class1, class2, class3 are never used in the code.





Aucun commentaire:

Enregistrer un commentaire