Running Scripts inside Java with ECMAScript

Something that’s in demand for every project being developed is configurability. These days, everything needs to be changeable. Languages, layouts, themes, colors, everything. In some projects, though, simply having a config file to load key values from is not enough. Sometimes people want to add simple scripts to their system, usually for automation.

In the project I’m working on now, I supply end users with a tool that allows the program to automatically purchase and sell cryptocurrency on trading platforms. The previous version of this for another client had some customizability, such as modifying the threshold for some numbers, but in large was tied to his desired criteria which was hardcoded.

The project I’m working on, though, I want to be 100% customizable. End users need to be able to specify their own criteria, given variables. The solution I found is to use Java’s script engine.

The ScriptEngine allows you to evaluate a script (in String or file form), running it and returning a value. The most common scripting language for use with ScriptEngine is JavaScript (a modified version of JavaScript to allow Java capabilities). There are an absolute ton of features you can use with it. For example, one cool feature allows you to use a script as implementation for a Java interface.

You can supply functions to the scripting engine, as well as objects. A common use for this would be a configurable filter. Say you had a list of Students, and you wanted to create a custom filter for them. Each student has the following data columns: Age, Name, Enrollment Date, Avg. Score. Given a Java object as a list of Java Student objects, you can pass this into a script definable by the user. It could look like this, where student is a student in the list (in Java, I would pass each student in the list to this script):

student.getAge() > 20 && student.getAverageScore() > 80

That would filter the list to only include students older than 20 and with an average test score over 80.