0

I'm quite new to building a custom annotation processor,
I've followed some tutorials & guides over here on SO too but been stuck on adding a condition for the annotated method.

The problem:
I have a custom annotation directed only for methods,
say, @RUN(isDebug: Boolean) & the method would be:

@RUN(isDebug = true)
private fun runInDebugOnly() {
    ....
}

@RUN(isDebug = false)
private fun runInReleaseOnly() {
    ....
}

So in my Annotation Processor,
is it possible to execute these functions with a condition?
I know the concept of generating a custom class & methods inside it,
But how to exactly intercept the method & use the generated method instead.

Any guidance would be appreciated.

Darshan
  • 4,020
  • 2
  • 18
  • 49
  • I don't think it's possible to implement this easily with kapt. Take a look at the [compiler plugins](https://resources.jetbrains.com/storage/products/kotlinconf2018/slides/5_Writing%20Your%20First%20Kotlin%20Compiler%20Plugin.pdf) which are much more powerful. [Here](https://bnorm.medium.com/writing-your-second-kotlin-compiler-plugin-part-1-project-setup-7b05c7d93f6c) is a nice article series on the topic. – esentsov Dec 26 '20 at 13:07
  • I think this is possible with an aspectj around advice, preventing the execution of the function based on the value given to the annotation. https://github.com/Archinamon/android-gradle-aspectj – Dani Jan 02 '21 at 12:02

1 Answers1

0

An annotation processor only runs at compile time, and is usually used to generate new classes or code.

Sounds to me like you want to generate a new method at compile time which will call the correct annotated method depending on the build type.

e.g. when you run a debug build you want to have

fun myNewMethod() {
   runInDebugOnly()
}

but when you run a release build you want to have

fun myNewMethod() {
   runInReleaseOnly()
}

The rest of your app will just call myNewMethod() and it won't care about the implementation.

You could achieve this another way without using an annotation processor

fun myNewMethod() {
   if (Build.DEBUG) {
     runInDebugOnly()
   } else if (Build.RELEASE) {
     runInReleaseOnly
   }
}

Is this the kind of thing you're after?

Andrew Kelly
  • 2,180
  • 2
  • 19
  • 27