|SourceBuddy Brings Eval To Java|
|Written by Nikos Vaggalis|
|Monday, 23 January 2023|
SourceBuddy is a Java library that compiles and loads dynamically generated Java source code. This has the advantage of providing Java with an eval facility such as those found in interpreted languages.
So given an input of $a=1, $b=2, $operator=+, eval will evaluate the expression "1 + 2" which gives 3.
To be extra cautious when needing to evaluate user supplied code; you don't want to compile and run a system("rm -rf") do you?
Eval can load whole libraries/modules at runtime as well like
$module = "My::module";
Of course in cases like that it is recommended to use more flexible solutions like Module::Load or Class::Load :
What about loading and evaluating code encapsulated into modules at runtime, from a file system path:
With SourceBuddy you can compile Java source code you created dynamically, in your Java application. Your program can create the source code of one or more Java classes, pass the strings to SourceBuddy and then use the classes. An example code is the following:
This is the same as Perl's simple string eval.To replicate Perl's runtime loading of modules from a file path you can use SourceBuddy's API call:
Why would you need this kind of functionality anyway? You use eval when the code to be evaluated is not known in advance, or even generated server-side. Yes, it's niche, but there are use cases.
In a sense this functionality is similar to that found in REPLing, where you can issue code at the shell which compiles and runs it as you go.
REPL, once an inherent property of the interpreted languages, has now found its way into compiled languages too.
So what's the deal with REPL? It's all about the immediate feedback loop you get; you can enter program elements one at a time, immediately see the result, and make adjustments as needed.
You can evaluate anything;variables, code blocks, functions, even define full-fledged classes and use them in the REPL console, always getting instant feedback, or even use C#/Java as a scripting language for testing purposes and running short lived utility scripts.
This comes in stark contrast with the typical workflow of working with a compiled language:
A REPL gives you the option to try out code without that hassle. You can test individual statements, try out different variations of a method, and experiment with unfamiliar APIs. Which makes it great for quick tutorials and prototypes.
For Java there's Jbang (jbang --interactive which uses JShell internally) and Jshell that serve the REPL's shell purpose.
In short, tools like Jbang and SourceBuddy act as extensions to the Java language bringing with them capabilities from interpreted languages.
CSharpRepl Brings REPL Superpowers To C#
|Last Updated ( Wednesday, 25 January 2023 )|