In my Android porject, I want to call static method on Kotlin class in a Gradle script. The class itself is part of a code base - it is
enum class and I want to call
MyEnumClass.values() on it in a gradle script.
How do I properly declare a dependency on the class, so I can call methods on it? Is it even possible?
Things I’ve tried:
That’s a chicken and egg problem. Gradle populates the build script classpath before firing the script, but you need the script to compile the class.
The only trick that comes to my mind would be to use the
buildSrc mechanism to inject the Kotlin enum in the build script classpath and configure the compiler to add
buildSrc/src/main/[...] to the source sets to compile.
I have done a lot of customization in past builds but I never went that far. When I open an old ‘unconventional’ build script, even though I put comments and tried to keep things clear, it always takes a while to understand again what was the point and why the magic kicks in. To keep things short, I’d advise you to keep a conventional layout, and break the dependency cycle by introducing a third party player that both the build and the code base can depend on. Why not a property file? or json or xml if key value is not enough? If you really want to keep a fully static code then it will require more work:
- move enum to a standalone project (let’s call it
- create gradle plugin (let’s class it
my-plugin that depends on
my-enum, you can create a fat jar for your plugin) that sole purpose is to do nothing
my-plugin binaries on a repository (you can first try a local disk repository to validate everything)
my-plugin to your build script, you should have access to your enum now in the build script
my-lib to your Android dependencies to have access to your enum in the code base
Pro, static all the way so you have type safety and speed
Con, when you need to update your enum, you have to publish 1 lib and 1 plugin and change 2 dependencies.
Thank you for an extensive reply. I think I’ll try the way with publishing the plugin.