Created
March 31, 2022 16:37
-
-
Save mehdiyari/b9944c68f783e52851fc3098092250b1 to your computer and use it in GitHub Desktop.
This gist is part of meta-programming with kotlin articles
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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