konewka
konewka

Reputation: 650

Retrieve code executed by function in Java

I'm trying to analyse some bits of Java-code, looking if the code is written too complexly. I start with a String containing the contents of a Java-class. From there I want to retrieve, given a function-name, the "inner code" by that function. In this example:

public class testClass{
    public int testFunction(char x) throws Exception{
        if(x=='a'){
            return 1;
        }else if(x=='{'){
            return 2;
        }else{
            return 3;
        }
    }
    public int testFunctionTwo(int y){
        return y;
    }
}

I want to get, when I call String code = getcode("testFunction");, that code contains if(x=='a'){ ... return 3; }. I've made the input code extra ugly, to demonstrate some of the problems one might encounter when doing character-by-character-analysis (because of the else if, the curly brackets will no longer match, because of the Exception thrown, the function declaration is not of the form functionName{ //contents }, etc.)

Is there a solid way to get the contents of testFunction, or should I implement all problems described manually?

Upvotes: 2

Views: 409

Answers (2)

bhdrk
bhdrk

Reputation: 3495

You need to a java parser. I worked too with QDox. it is easy to use. example here:

import com.thoughtworks.qdox.JavaProjectBuilder;
import com.thoughtworks.qdox.model.JavaClass;
import com.thoughtworks.qdox.model.JavaMethod;

import java.io.File;
import java.io.IOException;

public class Parser {

    public void parseFile() throws IOException {
        File file = new File("/path/to/testClass.java");

        JavaProjectBuilder builder = new JavaProjectBuilder();
        builder.addSource(file);

        for (JavaClass javaClass : builder.getClasses()) {
            if (javaClass.getName().equals("testClass")) {
                for (JavaMethod javaMethod : javaClass.getMethods()) {
                    if (javaMethod.getName().equals("testMethod")) {
                        System.out.println(javaMethod.getSourceCode());
                    }
                }
            }
        }
    }
}

Upvotes: 1

Brian Topping
Brian Topping

Reputation: 3295

Have you considered using a parser to read your code? There are a lot of parsers out there, the last time I worked on a problem like this http://qdox.codehaus.org made short work of these kinds of problems.

Upvotes: 1

Related Questions