How to exclude specific class in android gradle?

Need to exclude specific class only on release build variant. Could you please anyone give some pointers on it?


Solution 1:

In build.gradle file use:

android {
    compileSdkVersion 31
    
    defaultConfig {
        ...
    }
    buildTypes {
        ...
    }
    
    sourceSets {
        main {     //<-- flavour name (usual values are: "main", "release", debug")
            java {
                exclude '**/*_old.java'
                exclude '**/*_new.java'
                exclude '**/*_backup.java'
            }
        }
    }
}

Edited:

In /main/ flavour:

class ClassBase {
    
}

In /debug/ flavour:

class ClassA extends ClassBase {
    private ClassC mIncriminatedReference;  //<-- ClassC is the incriminated Class you won't
}

In /release/ flavour:

class ClassA extends ClassBase {
    /*no reference to ClassC here*/
}

then you can use/extend/instantiate ClassA (the right one will be choosen based on current active flavour) without errors when building for Release.

(I know it's tricky but it's the only way without using a custom PreProcessor as "plugin" while building)