Java Annotation Processor:检查TypeMirror是否实现特定的通用接口

问题描述 投票:4回答:1

我正在编写注释处理器,我需要检查特定的TypeMirror是否实现了特定的接口。问题Java Annotations Processor: Check if TypeMirror implements specific interface为非通用接口提供了答案。但它不适用于通用接口,例如String正在实现Comparable<String> - 并且使用isAssignable的代码不起作用。

此代码按预期工作:

TypeMirror tm = elementUtil.getTypeElement("java.lang.String").asType();
TypeMirror serializable = elementUtil.getTypeElement("java.io.Serializable").asType();
boolean isSerializable = typeUtil.isAssignable(tm, serializable);
//here isSerializable is true

但是这段代码没有:

TypeMirror tm = elementUtil.getTypeElement("java.lang.String").asType();
TypeMirror comparable = elementUtil.getTypeElement("java.lang.Comparable").asType();
boolean isComparable = typeUtil.isAssignable(tm, comparable);
//here isComparable is false

我认为,原因是,'可比'的TypeElement是用String作为通用参数定义的,但我不知道如何绕过它。

java generics annotations annotation-processing
1个回答
1
投票

qazxsw poi返回实际类型qazxsw poi。 qazxsw poi不能转让给Elements.getTypeElement,但可以加入Comparable<T>String。因此,最简单的方法是通过Comparable<T>擦除泛型类型。

Comparable<String>
© www.soinside.com 2019 - 2024. All rights reserved.