当方法具有泛型类型时,Eclipse JDT AST解析返回null

时间:2017-12-20 08:37:12

标签: java eclipse parsing eclipse-jdt

解析签名方法时:

<T> T get(int index);

呼叫:

c.<Object>get(1);

MethodInvocation。resolveMethodBinding()resolveTypeBinding(),返回null

但是,如果使用

调用它将返回绑定
c.get(1);

我需要找到一种方法来绑定所有的scnearios。

完整的案例:

public class MyTest {

    @Test
    public void test() throws IOException {
        Path path = Paths.get("src/main/java/ab/MyClass.java");

        TypeDeclaration typeDeclaration = getTypeDeclaration(path);
        typeDeclaration.accept(new ASTVisitor() {

            @Override
            public boolean visit(MethodInvocation node) {
                System.out.println(node.resolveMethodBinding());
                System.out.println(node.resolveTypeBinding());
                return true;
            }
        });
    }

    public static TypeDeclaration getTypeDeclaration(Path path) throws IOException {
        ASTParser parser = ASTParser.newParser(AST.JLS9);
        String value = new String(Files.readAllBytes(path), UTF_8);
        parser.setResolveBindings(true);
        parser.setBindingsRecovery(true);
        parser.setSource(value.toCharArray());
        parser.setKind(ASTParser.K_COMPILATION_UNIT);

        parser.setCompilerOptions(JavaCore.getOptions());

        parser.setUnitName(path.getFileName().toString());

        String[] classpathEntries = {};
        String[] sourcepathEntries = { "C:\\test\\src\\main\\java" };

        parser.setEnvironment(classpathEntries, sourcepathEntries,
                new String[] { UTF_8.name() }, true);

        final CompilationUnit cu = (CompilationUnit) parser.createAST(null);

        return (TypeDeclaration) cu.types().get(0);
    }
}
public interface SomeInterface {

    <T> T get(int index);
}
public abstract class AbstractClass implements SomeInterface {

}
public class MyClass {

    AbstractClass c;

    public MyClass() {
        c.<Object>get(1);
    }
}

类似问题(2017945263198112755640)没有相关答案。

1 个答案:

答案 0 :(得分:0)

实际上,这是因为需要指定COMPILER_SOURCE

Hashtable<String, String> options = JavaCore.getOptions();
options.put(JavaCore.COMPILER_SOURCE, "1.8");
parser.setCompilerOptions(options);