Java/Kotlin annotation processor: get type of anno

2019-08-21 09:08发布

问题:

For example I have a class:

class Foo {
  @AnnotatedProp
  var foo: Boolean? = null
}

How can I get type of foo property in my custom annotation processor? in pseudo I'd expect something like: annotatedElement.getStringifiedReturnTypeSomehow() //returns "Boolean"

回答1:

The way I've done it, ensure your annotation has an AnnotationTarget.FIELD target.

Than after you get the Element instance with required annotation, just: val returnTypeQualifiedName = element.asType().toString() if you want to find out if it's nullable:

private fun isNullableProperty(element: Element): Boolean {
        val nullableAnnotation = element.getAnnotation(org.jetbrains.annotations.Nullable::class.java)
        if (nullableAnnotation == null) {
            return false
        } else {
            return true
        }
    }


回答2:

You can use reflection to get what you need.

import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.full.findAnnotation
import kotlin.reflect.full.starProjectedType

annotation class AnnotatedProp

class Foo {
    @AnnotatedProp
    var foo: Boolean? = null
    var bar: String? = null
}

fun main(args: Array<String>) {

    // Process annotated properties declared in class Foo.
    Foo::class.declaredMemberProperties.filter {
        it.findAnnotation<AnnotatedProp>() != null
    }.forEach {
        println("Name: ${it.name}")
        println("Nullable: ${it.returnType.isMarkedNullable}")
        println("Type: ${it.returnType.classifier!!.starProjectedType}")
    }

}

This will print out:

Name: foo
Nullable: true
Type: kotlin.Boolean

Kotlin's standard library does not come with reflection, so be sure to add

compile "org.jetbrains.kotlin:kotlin-reflect:$version_kotlin"

to your Gradle build file.