With ASTParser, how can I resolve bindings for instance creation with diamond operator? ClassInstanceCreation#resolveConstructorBinding method returns null when diamond operator is used.
Following is the target source to parse.
package foo.bar;
import java.util.*;
public class SampleDiamondOperator {
public void invoke() {
Map<String, String> map1 = new HashMap<String, String>(); // Binding is resolved for this one ...
Map<String, String> map2 = new HashMap<>(); // but not for this one
}
}
When the above source is parsed with the following code, second instance creation cannot be binded.
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/SampleDiamondOperator.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);
final CompilationUnit unit = (CompilationUnit) ast;
unit.accept(new ASTVisitor() {
@Override
public boolean visit(ClassInstanceCreation node) {
System.out.println(lineNumberOf(node) + ": " + node + " -> " + node.resolveConstructorBinding());
return true;
}
private int lineNumberOf(ASTNode node) {
return unit.getLineNumber(node.getStartPosition());
};
});
}
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);
}
}
}
Here is the result of executing the above.
9: new HashMap<String,String>() -> public void <init>()
10: new HashMap<>() -> null