Java.
This Java 6 code uses the URLClassLoader class to load and invoke a selection of engines at runtime:
Note that the
ClassLoader used to load the engine is
set as the context
ClassLoader around any calls to the
engine. Failure to do this may result in errors.
Expected output:
Hello, ECMAScript! Hello, Groovy! Hello, JRuby! Hello, Jython!
Configuration
As well as the libraries for the scripting languages, some of the implementations require a third-party scripting engine from scripting.dev.java.net. Later versions may include support by default, in which case the external library can be dropped from the classpath.
Run on a Windows PC, the code uses the following environment variables set to the library installation directories:
GROOVY_HOME=C:\Java\groovy-1.6.0 JRUBY_HOME=C:\Java\jruby-1.2.0 JYTHON_HOME=C:\Java\jython2.2.1 SCRIPT_ENGINES=C:\Java\jsr223-engines
I am trying to use this approach to load the latest version of Rhino. My environment has an older version already implemented, and I cannot seem to load the new one, even when I use the URL class loader AND create a script engine manager with that class loader as well.
Is it possible to override something that's already built in?
ClassLoaders will try to load any given class from the parent ClassLoader first, so anything on the JRE classpath will be loaded before anything specific to a given URLClassLoader.
That said, anything that goes into the JRE usually gets its own com.sun.foo namespace to avoid collisions, so there shouldn't be a problem here.
I was able to invoke Rhino (rhino1_7R2) by adding the following command to the above program:
invokeScript(
"ECMAScript",
"print('Hello, Rhino!');",
System.getenv("SCRIPT_ENGINES")
+ "/javascript/build",
System.getenv("ECMA_HOME"));
ECMA_HOME just contains js.jar. Note that I used an engine from the set described in the post.