获取带注释的字段

获取带注释的字段

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

问题描述

例如,我有一个课程:

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

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

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注释处理器:获取带注释的字段/属性的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 13:32