views:

39

answers:

1

Hi, 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.JLS3);
    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

A: 

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.

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

zvikico
Thanks a lot for your reply. This has been helpful.
Fahim
I'm glad it helped. Now, mark it as the correct answer :-)
zvikico