gsonpath.adapter.util.AdapterFactoryUtil.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of gsonpath-compiler Show documentation
Show all versions of gsonpath-compiler Show documentation
An annotation processor which generates Type Adapters for the Google Gson library
package gsonpath.adapter.util
import com.squareup.javapoet.ClassName
import javax.annotation.processing.RoundEnvironment
import javax.lang.model.element.ElementKind
import javax.lang.model.element.TypeElement
object AdapterFactoryUtil {
inline fun getAnnotatedModelElements(
env: RoundEnvironment,
annotations: Set,
supportedElementKinds: List = listOf(ElementKind.CLASS)): Set> {
val supportedAnnotations = getSupportedAnnotations(annotations, T::class.java)
val customAnnotations = getCustomAnnotations(annotations, T::class.java)
// Avoid going any further if no supported annotations are found.
if (supportedAnnotations.isEmpty() && customAnnotations.isEmpty()) {
return emptySet()
}
return env
.getElementsAnnotatedWith(T::class.java)
.asSequence()
.filter { supportedElementKinds.contains(it.kind) }
.map {
ElementAndAnnotation(it as TypeElement, it.getAnnotation(T::class.java))
}
.filter {
!customAnnotations.contains(it.element)
}
.plus(
customAnnotations.flatMap { customAnnotation ->
env
.getElementsAnnotatedWith(customAnnotation)
.filter { supportedElementKinds.contains(it.kind) }
.map {
ElementAndAnnotation(it as TypeElement, customAnnotation.getAnnotation(T::class.java))
}
}
)
.toSet()
}
fun getSupportedAnnotations(annotations: Set, annotationClassName: Class) =
annotations
.asSequence()
.map(ClassName::get)
.filter { it == ClassName.get(annotationClassName) }
.toList()
fun getCustomAnnotations(annotations: Set, annotationClassName: Class) =
annotations.filter { it.getAnnotation(annotationClassName) != null }
}
data class ElementAndAnnotation(
val element: TypeElement,
val annotation: T
)