I am building 4 different flavors of my Android app.
I have a class Customization.java that is the same for 3 of them and different for 1.
Since
I use this to override codes for 5 years, just add a piece of code to your build.gradle.
For lastest gradle plugin(>=3.4.0):
android {
......
applicationVariants.configureEach { ApplicationVariant variant ->
AndroidSourceSet flavorSourceSet = android.sourceSets.findByName(variant.productFlavors[0].name);
if (flavorSourceSet != null) {
String flavorPath = flavorSourceSet.java.srcDirs[0].path;
variant.javaCompileProvider.configure { task ->
task.exclude { FileTreeElement elem ->
!elem.isDirectory() && !elem.file.parent.startsWith(flavorPath) &&
new File(flavorPath, elem.path).exists();
}
}
}
}
For older gradle plugin:
android {
......
applicationVariants.all { ApplicationVariant variant ->
AndroidSourceSet flavorSourceSet = android.sourceSets.findByName(variant.productFlavors[0].name);
if (flavorSourceSet != null) {
variant.javaCompiler.doFirst {
String flavorPath = flavorSourceSet.java.srcDirs[0].path;
variant.javaCompiler.exclude { FileTreeElement elem ->
!elem.isDirectory() && !elem.file.parent.startsWith(flavorPath) &&
new File(flavorPath, elem.path).exists();
}
}
}
}
It'll find duplicate classes in the Main sourceset and then exclude it during compile to avoid class duplicate error.