简体   繁体   English

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

[英]Java/Kotlin annotation processor: get type of annotated field/property

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? 如何在自定义注释处理器中获取foo属性的类型? in pseudo I'd expect something like: annotatedElement.getStringifiedReturnTypeSomehow() //returns "Boolean" 用伪代码,我期望像这样: annotatedElement.getStringifiedReturnTypeSomehow() //returns "Boolean"

The way I've done it, ensure your annotation has an AnnotationTarget.FIELD target. 我这样做的方式,请确保您的注释具有AnnotationTarget.FIELD目标。

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: 在获得带有必需注释的Element实例之后,如果要查找它是否可为空,则只需: val returnTypeQualifiedName = element.asType().toString()

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

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 Kotlin的标准库不带有反射,因此请务必添加

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

to your Gradle build file. 到您的Gradle构建文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM