Check return type of ExecutableElement is subtype of Collection

Phuong Hoang :

I have an ExecutableElement representing a getter, an example is the one below.

public List<String> getStrings();

The only method that allows me to get the details of the return type is ExecutableElement.getReturnType(). It gives me back a TypeMirror.

I could not find anything that allows me to check if TypeMirror returned is a subtype of Collection. What can I do to verify that? I am trying to generate the source code to call one of the methods in Collection.

i.bondarenko :

You could have a look at 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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=148314&siteId=1