我正在编写注释处理器,我需要检查是否有特定的 TypeMirror
实现特定接口(interface)。
问题Java Annotations Processor: Check if TypeMirror implements specific interface为非通用接口(interface)提供答案。
但它不适用于通用接口(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 作为通用参数定义的,但我不知道如何绕过它。
最佳答案
Elements.getTypeElement
返回实际类型 Comparable<T>
. String
不可分配给 Comparable<T>
但可以分配给Comparable<String>
或 Comparable
.所以最简单的方法是通过 Types.erasure(TypeMirror)
删除通用类型.
TypeMirror tm = elements.getTypeElement("java.lang.String").asType();
TypeMirror comparable = types.erasure(elements.getTypeElement("java.lang.Comparable").asType());
boolean isComparable = types.isAssignable(tm, comparable); // return true
关于Java 注释处理器 : check if TypeMirror implements specific generic interface,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47553977/