【问题标题】:Check return type of ExecutableElement is subtype of Collection检查 ExecutableElement 的返回类型是 Collection 的子类型
【发布时间】:2020-01-08 14:45:14
【问题描述】:

我有一个代表 getter 的ExecutableElement,下面是一个示例。

public List<String> getStrings();

让我获得返回类型详细信息的唯一方法是ExecutableElement.getReturnType()。它给了我一个TypeMirror

我找不到任何可以让我检查返回的TypeMirror 是否是Collection 的子类型的东西。我能做些什么来验证这一点?我正在尝试生成源代码来调用Collection 中的方法之一。

【问题讨论】:

标签: java java-annotations


【解决方案1】:

你可以看看 org.netbeans.modules.java.hints.jdk.mapreduce.PreconditionsChecker

private boolean isIterbale(ExpressionTree expression) {
    TypeMirror tm = workingCopy.getTrees().getTypeMirror(TreePath.getPath(workingCopy.getCompilationUnit(), expression));
    if (!Utilities.isValidType(tm)) {
        return false;
    }
    if (tm.getKind() == TypeKind.ARRAY) {
        return false;
    } else {
        tm = workingCopy.getTypes().erasure(tm);
        TypeElement typeEl = workingCopy.getElements().getTypeElement("java.util.Collection");
        if (typeEl != null) {
            TypeMirror collection = typeEl.asType();
            collection = workingCopy.getTypes().erasure(collection);
            if (this.workingCopy.getTypes().isSubtype(tm, collection)) {
                return true;
            }
        }
    }

    return false;
}

PreconditionsChecker

【讨论】:

  • 非常感谢。这正是我所需要的。
  • @PhuongHoang 特别注意Types#erasure(TypeMirror)的使用。
  • @Slaw 我确实注意到使用了擦除。我假设这是为了比较 Collection 的原始类型。这是你的意思吗?
  • @PhuongHoang 是的。否则,您正在测试参数化类型。
猜你喜欢
  • 1970-01-01
  • 2019-06-28
  • 1970-01-01
  • 2016-08-03
  • 2011-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多