检查 return 类型的 ExecutableElement 是 Collection 的子类型

Check return type of ExecutableElement is subtype of Collection

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

public List<String> getStrings();

唯一能让我获得 return 类型详细信息的方法是 ExecutableElement.getReturnType(). It gives me back a TypeMirror

我找不到任何可以让我检查 TypeMirror returned 是否是 Collection. What can I do to verify that? I am trying to generate the source code to call one of the methods in Collection.

的子类型的东西

你可以看看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