【问题标题】:Eclipse JDT AST parsing returns null when method has a generic type当方法具有泛型类型时,Eclipse JDT AST 解析返回 null
【发布时间】:2017-12-20 08:37:11
【问题描述】:

解析签名方法时:

<T> T get(int index);

调用:

c.<Object>get(1);

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

但是,如果调用它会返回一个绑定

c.get(1);

我需要找到一种方法来绑定所有场景。

完整案例:

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)没有相关答案。

【问题讨论】:

    标签: java eclipse parsing eclipse-jdt


    【解决方案1】:

    其实是因为COMPILER_SOURCE需要指定:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多