Question

How can I infer the type of a nested method call such as:

JavaSourceFile javaSourceFile = new JavaSourceFile();

javaSourceFile.getClasses().size()

It works for normal method calls such as

javaSourceFile.getClasses()

But i would like to obtain the return type of getClasses(). This is what I do. In

ASTVisitor.visit(MethodInvocation invocation) 

I want to obtain the type of the size() call. I use

    Expression expression = invocation.getExpression();
    if (expression != null) {

        ITypeBinding typeBinding = expression.resolveTypeBinding();
        if (typeBinding != null) {
            Call call = new Call(invocation.getName().getFullyQualifiedName(), typeBinding.getName());
            this.activeMethod.getCalls().add(call);
        }
    }

to obtain the type of a method invocation. But if there there is a method call as in outlined at the start I just get null. I also use

invocation.resolveMethodBinding();

afterwards if the binding couldn't be resolved using the expression.

Was it helpful?

Solution

In this example you have 2 method invocations. So your visitor will be called 2 times unless you return false.

First time you visit with this expression javaSourceFile.getClasses().size() and if you call resolveTypeBinding() you will actually get the type of size() method because it happens first.

However in your given code if your visitor was called with javaSourceFile.getClasses().size() then you are actually resolving type for javaSourceFile.getClasses(), because you used getExpression() method. (NOTE: if your visit method didn't return false it will be visited again as javaSourceFile.getClasses() (since it's method invocation as well) and then you will get type of javaSourceFile variable)

Also you said that you get null which I believe shouldn't happen if everything is set up properly (for example maybe you didn't specify classpaths/sourcepaths of some classes). Can't tell why that happens since I need full code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top