Java / Kotlin注释处理器:获取注释字段/属性的类型

例如我有一个类:

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

我如何获得我的自定义注释处理器中的foo属性的类型? 在伪我希望这样的事情annotatedElement.getStringifiedReturnTypeSomehow() //returns "Boolean"

你可以使用反射来得到你所需要的。

 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}") } } 

这将打印出来:

 Name: foo Nullable: true Type: kotlin.Boolean 

Kotlin的标准库不会附带反射,所以一定要添加

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

到您的Gradle构建文件。

我已经做到这一点,确保您的注释有一个AnnotationTarget.FIELD目标。

在获得具有所需注释的Element实例之后,只需要: val returnTypeQualifiedName = element.asType().toString()如果你想知道它是否可以为null:

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