Skip to content

Instantly share code, notes, and snippets.

@mehdiyari
Created March 31, 2022 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mehdiyari/b9944c68f783e52851fc3098092250b1 to your computer and use it in GitHub Desktop.
Save mehdiyari/b9944c68f783e52851fc3098092250b1 to your computer and use it in GitHub Desktop.
This gist is part of meta-programming with kotlin articles
/**
* This is simple processor that use JSR-269 API and kotlinpoet library to generate
* extension function for annotated classes with [HelloWorldAnnotation]
*/
class HelloWorldProcessor : AbstractProcessor() {
override fun process(annotations: MutableSet<out TypeElement>?, roundEnv: RoundEnvironment?): Boolean {
val typeElement = annotations?.firstOrNull() ?: return false
for (annotatedElement in roundEnv?.getElementsAnnotatedWith(typeElement) ?: setOf()) {
val elementPackageName = processingEnv.elementUtils.getPackageOf(annotatedElement).qualifiedName.toString()
FileSpec.builder(
packageName = elementPackageName,
fileName = "${annotatedElement.simpleName}_Generated"
).also { currentClassFileSpec ->
FunSpec.builder("printHelloWorld").receiver(
ClassName(
elementPackageName,
annotatedElement.simpleName.toString()
)
).addStatement("println(\"Hello world!\")").build().also(currentClassFileSpec::addFunction)
}.build().writeTo(processingEnv.filer)
}
return true
}
override fun getSupportedAnnotationTypes(): MutableSet<String> = mutableSetOf<String>().apply {
add(HelloWorldAnnotation::class.java.canonicalName)
}
override fun getSupportedSourceVersion(): SourceVersion = SourceVersion.latestSupported()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment