如何解决标注处理时如何检查Element代表的类是否为指定类的子类型?
@SomeAnnotation
data class Foo(
@Serializedname("str")
val stringValue: String = "",@Serializedname("int")
val intValue: Int = 0,@Serializedname("list")
val listValue: List<Long> = listof()
)
在注释处理过程中,我无法检查 Foo 类的字段是否为 kotlin.collections.Collections
(如 List、Set)
我的注释处理器是这样的:
class SomeAnnotationProcessor: AbstractProcessor() {
fun processSomeAnnotation(clazz: Element) {
clazz.enclosedElements.asSequence().filter {
it.kind == ElementKind.FIELD && !it.modifiers.contains(Modifier.STATIC)
}.map {
// how to check if the fields' of clazz is Collections?
// I just kNow how to obtain parameterize type of this field like this
(it as Symbol).type.typeArguments
}.toList()
}
}
这是检查元素的所有字段是否是指定类的子类型(如 kotlin.collections.Collections
)的任何方法?谢谢。
解决方法
在java中我使用这个
/**
* Checks if the element type is assignable of the target class (i.e. if it's a derivative type of
* it)
*
* @param element the element
* @param targetClass the target class
* @return true if the element is assignable from the target class,false otherwise
*/
public boolean isAssignableFrom(Element element,Class<?> targetClass) {
return isAssignableFrom(element.asType(),targetClass);
}
/**
* Checks if the type mirror is assignable of the target class (i.e. if it's a derivative type of
* it)
*
* @param typeMirror the type mirror
* @param targetClass the target class
* @return true if the type mirror is assignable from the target class,false otherwise
*/
public boolean isAssignableFrom(TypeMirror typeMirror,Class<?> targetClass) {
return types.isAssignable(
typeMirror,types.getDeclaredType(elements.getTypeElement(targetClass.getCanonicalName())));
}
其中类型是 javax.lang.model.util.Types
和元素是 javax.lang.model.util.Elements
两者都可以从 ProcessingEnvironment
获得
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。