java源解析,查找具有完整类型的方法签名

时间:2017-02-13 21:08:28

标签: java parsing binding javaparser

我正在使用

javaparser(https://github.com/javaparser/javaparser)和 javasymbolsolver(https://github.com/javaparser/javasymbolsolver)。

解析java源代码。我希望从.java文件创建一个基本报告来列出方法签名,如果它们包含完整的java类型,那将会很好。

这是javaparser'访问'的基本合并。演示和javasymbolsolver演示,但我遇到了困难。

炸毁' getType'打电话,

Exception in thread "main" java.lang.UnsupportedOperationException: com.github.javaparser.ast.type.ClassOrInterfaceType
    at me.tomassetti.symbolsolver.javaparsermodel.JavaParserFacade.getTypeConcrete(JavaParserFacade.java:392)

这是(非工作)代码,

static CombinedTypeSolver combinedTypeSolver;

public static void main(String[] args) throws Exception {
    combinedTypeSolver = new CombinedTypeSolver();
    combinedTypeSolver.add(new JreTypeSolver());
    combinedTypeSolver.add(new JarTypeSolver("C:/source.jar"));
    combinedTypeSolver.add(new JavaParserTypeSolver(new File("C:/src")));

    FileInputStream in = new FileInputStream("C:/src/source.java");
    CompilationUnit cu = JavaParser.parse(in);
    new MethodVisitor().visit(cu, null);
}

private static class MethodVisitor extends VoidVisitorAdapter<Void> {
    public void visit(MethodDeclaration n, Void arg) {

        Node node = n.getType();
        System.out.println(node);
        TypeUsage typeOfTheNode = JavaParserFacade.get(combinedTypeSolver).getType(node);

        super.visit(n, arg);
    }


}

1 个答案:

答案 0 :(得分:2)

我建议您在ReflectionTypeSolver添加CombinedTypeSolver。 然后,为了获得所有MethodDeclaration的列表,我使用

List<MethodDeclaration> l = Navigator.findAllNodesOfGivenClass(cu, MethodDeclaration.class);

然后我将每个MethodDeclaration(JavaParser)包装在JavaParserMethodDeclaration中,就像那样

for(MethodDeclaration md : l){
     System.out.println(new JavaParserMethodDeclaration(mdec, facade.getTypeSolver()).getQualifiedSignature());
}