How to resolve bindings for statically imported methods [message #1439333] |
Tue, 07 October 2014 04:12  |
Eclipse User |
|
|
|
I'm using ASTParser to analyze source code.
When I call resolveMethodBinding() in MethodInvocation class, it returns null when the MethodInvocation instance is for statically imported method invocations. It works fine for all the other invocations. What am I missing?
import static foo.bar.Other.methodA;
public class Sample {
public void invoke() {
Other.methodA(); // Binding is resolved for this one ...
methodA(); // but not for this one.
}
}
I've tried with following versions of org.eclipse.jdt.core.
- 3.10.0
- 3.6.51
|
|
|
|
|
|
Re: How to resolve bindings for statically imported methods [message #1440935 is a reply to message #1440491] |
Thu, 09 October 2014 03:27   |
Eclipse User |
|
|
|
Following is the parsing code.
package ast.sample;
import java.io.*;
import java.nio.charset.*;
import java.nio.file.*;
import org.eclipse.jdt.core.dom.*;
public class TestASTParser {
private static final String PROJECT_ROOT = System.getProperty("user.dir");
private static final Path SOURCE_PATH = Paths.get(PROJECT_ROOT, "/src/foo/bar/Sample.java");
private static final String[] CLASS_PATH_ENTRIES = new String[] {PROJECT_ROOT + "/bin"};
public static void main(String... args) {
ASTParser parser = ASTParser.newParser(AST.JLS8);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setEnvironment(CLASS_PATH_ENTRIES, null, null, true);
parser.setResolveBindings(true);
parser.setSource(readAsCharArray(SOURCE_PATH));
parser.setUnitName(SOURCE_PATH.toString());
ASTNode ast = parser.createAST(null);
CompilationUnit unit = (CompilationUnit) ast;
unit.accept(new ASTVisitor() {
@Override
public boolean visit(MethodInvocation node) {
int lineNumber = unit.getLineNumber(node.getStartPosition());
System.out.println(lineNumber + ": " + node + " -> " + node.resolveMethodBinding());
return true;
};
});
}
private static char[] readAsCharArray(Path path) {
try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
StringBuilder buffer = new StringBuilder();
int c = -1;
while ((c = reader.read()) != -1) {
buffer.append((char) c);
}
return buffer.toString().toCharArray();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
And following is the target source file.
package foo.bar;
import static foo.bar.Other.methodA;
public class Sample {
public void invoke() {
Other.methodA(); // Binding is resolved for this one ...
methodA(); // but not for this one.
}
}
When I execute the first program, I get the following result which indicates that it had failed to resolve binding for the second invocation of methodA.
7: Other.methodA() -> public static void methodA()
8: methodA() -> null
|
|
|
|
Powered by
FUDForum. Page generated in 5.26893 seconds