Java/Kotlin 注释处理器:获取注释字段/属性的类型 [英] Java/Kotlin annotation processor: get type of annotated field/property

查看:52
本文介绍了Java/Kotlin 注释处理器:获取注释字段/属性的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我有一堂课:

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

如何在我的自定义注释处理器中获取 foo 属性的类型?在伪我希望是这样的:annotatedElement.getStringifiedReturnTypeSomehow()//返回布尔值"

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

推荐答案

按照我的做法,确保您的注释具有 AnnotationTarget.FIELD 目标.

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

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

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

这篇关于Java/Kotlin 注释处理器:获取注释字段/属性的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆