Skip to content
Advertisement

Executing Java code inside a Java program

I would like to create an application which for example measures the execution time of a certain block of code. In this case it should have a structure like this:

public static long measureExecution(String code){
    long start = System.nanoTime();
    executeCode(code); // <----
    long time = System.nanoTime() - start;

    return time;
}

I’m curious about the method designated by the arrow, I need some sort of a placeholder. How should be this method implemented? Is it even possible to execute a custom Java code inside running Java application?

I was thinking that it can be done with some sort of overriding of another methods body, but I can’t quite figure out how.

Thanks for your opinions!

Advertisement

Answer

You could pass a Runnable:

public static long measureExecution(Runnable code) {
    long start = System.nanoTime();
    code.run();
    long time = System.nanoTime() - start;
    return time;
}

At the place where you call the method, use an anonymous inner class to wrap the code you want to measure:

long time = measureExecution(new Runnable() {

    @Override
    public void run() {
        System.out.println("Do something");
    }
});

(If you were using Java 8, you could use a lambda expression instead of an anonymous inner class, which would make the code shorter and easier to read).

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement