Why Can You Execute Java-Code From A JS-ScriptEngine Eval(String)?

- 1 answer

After setting up a JavaScript-ScriptEngine like this:

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

public class Compute {

  public static void main(String[] args){

      ScriptEngineManager mgr = new ScriptEngineManager();
      ScriptEngine engine = mgr.getEngineByName("JavaScript");

    catch(Exception e){
      System.out.println("Syntax Error!");


Why can you do things like: java Compute "java.util.Arrays.toString(new\".\").listFiles())"

Isn't the ScriptEngine for "JavaScript" supposed to execute JS only?

Any links on what the Engine actually does or why this is possible, would be greatly appreciated.

(edit: This is no duplicate of security problem with Java ScriptEngine, as I want to know why this is possible, not how to avoid it)



You have to stop and think for a moment what exactly a scripting engine is used for. To quote the officicial documentation (which is a recommended read on the topic):

With the Java Scripting API, it is possible to write customizable/extendable applications in the Java language and leave the customization scripting language choice to the end user

The point is you write your big old application in Java, and then have another party (which could be the end user, application developers using your "engine/framework", or dedicated consultants if you are an Enterprise-level shop) customize it to suit their needs.

This customization takes place in a non-compiled language (i.e. script), like javascript (ECMAScript). The scripting engine allows interaction with the Java classes in exactly the way your little test script demonstrates. After all, this interaction is the whole point of having a scripting engine in the first place.