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!
Have you ever thought if it's possible to compile and run a java program from another java program? We can use Runtime. exec(String cmd) to issue commands to the underlying operating system. We will use the same approach to compile and run a java program from another java program.
In Java, programs are not compiled into executable files; they are compiled into bytecode (as discussed earlier), which the JVM (Java Virtual Machine) then executes at runtime. Java source code is compiled into bytecode when we use the javac compiler.
🖥️ How to Run the Java Code class file to execute the Java programs. For that, we use the command java class_file_name_without_the_extension . Like, as our . class file for this is Main.
In JavaSW, you can run another application by calling the exec method on the Runtime object, which may be obtained via a call to Runtime. getRuntime().
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).
You can use OpenHFT/Java-Runtime-Compiler:
https://github.com/OpenHFT/Java-Runtime-Compiler
Also, you can use ToolProvider class (Compiler API), since java 1.6:
private Path compileJavaFile(Path javaFile, String className) {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(null, null, null, javaFile.toFile().getAbsolutePath());
return javaFile.getParent().resolve(className);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With