does anyone here have experience with kotlinpoet and annotation processing? I want to add a method to an existing class
l
louiscad
01/11/2018, 1:44 PM
I don't think you can add code to non generated classes with kotlinpoet or other annotation processors. The kotshi library uses javapoet to write JSON adapters in Java for Kotlin models. This could help you get started, and you can probably apply what you may learn there to kotlinpoet
g
gildor
01/12/2018, 3:28 AM
@tschuchort It’s impossible. Java Annotation Processing standard JSR-269 doesn’t support mutation of existing code, only generation of new code. And it’s not kotlinpoet restriction, KotlinPoet tool that allow you to write Kotlin code programmatically, but APT doesn’t allow to do that (same as kapt, that uses this standard to support existing annotation processors).
The only way to add methods and so on it’s bytecode manipulation (you can check Android Gradle Trasnform API as an example of such approach - http://tools.android.com/tech-docs/new-build-system/transform-api)
Or Kotlin Compiler Plugins. There is a few of them from Kotlin Team, but this API is not public and not stable, so not intended to use by third party developers for now.
There are some other techniques that allow you to emulate this. For example you can generate class that extends your existing class and adds method, but this approach of course has a lot of problems. You can check AndroidAnnotations library that use such technique. And on my experience it’s really bad approach that pollute your code a lot.
👍 2
t
tschuchort
01/12/2018, 3:07 PM
oh that sucks. Looks like my only option is to use a compiler plugin and transform api then, like the smuggler library for generating Parcelable implementations. I just want to add a few methods to a data class, but apparently it's not as easy as I though it would be
g
gildor
01/13/2018, 2:51 AM
Compiler plugin for now it's not a real option tho. I'm not sure that there is exist any third party plugin,. Also API is not stable, so you would probably support it and fix each release of Kotlin