1

I need to be able to get information about the constructor of a source file, for example the beging line number, and maybe some lines that are within the constructor. I am using a similar idea for the methods of a file in order to be able to get the begin and end line numbers and the names of the methods. For this im using the JavaParser as explained in here.

I could not find a way to be able to use the JavaParser for my aim. Is there a way to be able to get similar information of the constructor?

Community
  • 1
  • 1
ict1991
  • 2,060
  • 5
  • 26
  • 34

2 Answers2

2

You can get information about the constructor the same way you do it with method declarations:

CompilationUnit cu = JavaParser.parse(file);
    List<TypeDeclaration> typeDeclarations = cu.getTypes();
    for (TypeDeclaration typeDec : typeDeclarations) {
        List<BodyDeclaration> members = typeDec.getMembers();
        if(members != null) {
            for (BodyDeclaration member : members) {
                if (member instanceof ConstructorDeclaration) {
                    ConstructorDeclaration constructor = (ConstructorDeclaration) member;
                    //Put your code here
                    //The constructor instance contains all the information about it. 

                    constructor.getBeginLine(); //begin line
                    constructor.getBlock(); //constructor body
                }
            }
        }
    }
poozmak
  • 414
  • 2
  • 11
0

You should look into using the Java perser from Eclipse Java Development Tools (JDT). There is an excellent tutorial with code examples by Lars Vogel: Eclipse JDT - Abstract Syntax Tree (AST) and the Java Model - Tutorial on how to parse java code.

You can get the IMethod for every constructor and then call getSourceRange() and getSource() on it.

Andrejs
  • 26,885
  • 12
  • 107
  • 96