开发者

Eclipse ASTParser to parse only a java function?

开发者 https://www.devze.com 2023-01-11 17:49 出处:网络
I just wanna know using org.eclipse.jdt.core.dom.ASTParser if it is possible to parse only a java function?

I just wanna know using org.eclipse.jdt.core.dom.ASTParser if it is possible to parse only a java function?

This is how I tried: I passed the code of a function to the ASTParser.setSource(char[] s) as follows:

    ASTParser parser = ASTParser.newParser(AST.JL开发者_StackOverflow中文版S3);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setSource(unit); //set source
    CompilationUnit cu = (CompilationUnit) parser.createAST(null /* IProgressMonitor */); // parse
    List list = node.types();
    for(int i = 0; i < list.size(); i++){
       ASTNode typeNode = (ASTNode) list.get(i);
       System.out.println(ASTNode.nodeClassForType(typeNode.getNodeType()));
    }

But I see that the list of types contains nothing (size = 0).

Please suggest. Thanks. Fahim


Just a small typo, in the line List list = node.types(); it should be List list = cu.types();. You cannot pass a function only. It needs to be valid Java compilation unit, so it must have a type definition. Make sure you wrap your function with a class. Any class. It should work just fine.

If it doesn't work, remember that you can ask for cu.getProblems() and see where it failed.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号