我的 Java 注释处理器正在生成一个接口的实现,该接口有一个返回
MyInterface.foo()
的 CompletableFuture<String>
方法。在我的处理器中,该方法的 ExecutableElement
表示 getReturnType()
TypeMirror
,其 toString()
值为 java.util.concurrent.CompletableFuture<java.lang.String>
,所以我知道我有正确的 TypeMirror
作为返回类型。
现在我想在代码中测试这个
TypeMirror
实例是否确实是某种 CompletableFuture
。我尝试了Types.isAssignable(…)
、Types.isSubtype(…)
和Types.isSameType(…)
,但似乎都不起作用。例如:
TypeElement completableFutureTypeElement = processingEnv.getElementUtils()
.getTypeElement(CompletableFuture.class.getCanonicalName());
boolean isCompletableFutureReturnType = processingEnv.getTypeUtils()
.isSubtype(returnTypeMirror, completableFutureTypeElement.asType())
我是否使用了错误的检查方法?或者问题是返回类型是
CompletableFuture<String>
并且我正在与原始类型进行比较?在任何情况下,我如何简单地检查返回类型的非参数化(即原始)类是否为CompletableFuture
?我想我可以只比较字符串,但是有更多类型安全、语义的方式吗?
我的相关问题是如何为已知的类获得
TypeMirror
,就像我上面为 completableFutureTypeElement
然后为 completableFutureTypeElement.asType()
所做的那样。有没有更直接的方法来获取诸如 TypeElement
之类的类的 TypeMirror
和/或 CompletableFuture.class
而不对其名称的字符串形式进行查找?
目前我最好的猜测是比较不起作用,因为我正在将原始类型与实际参数化类型进行比较。如果我将 return
TypeMirror
转换为 DeclaredType
,获取其 Element
表示,然后转换回 TypeMirror
,则比较有效:
TypeElement completableFutureTypeElement = processingEnv.getElementUtils()
.getTypeElement(CompletableFuture.class.getCanonicalName());
boolean isCompletableFutureReturnType = processingEnv.getTypeUtils()
.isSubtype(((DeclaredType)returnTypeMirror).asElement().asType(),
completableFutureTypeElement.asType())
不过,我不确定这是否是解决此问题的最佳方法。此外,我似乎无法将
isSubtype(…)
或 isAssignable(…)
与 Future
一起使用,即使 CompletableFuture
实现了 Future
;所以我这里可能缺少一些更合适的技术。