Using Nashorn with interfaces loaded from custom classloaders

Christopher Brown christopherbrown06 at
Fri Feb 6 09:05:36 UTC 2015


Is it possible to use the Java.type() then the Java.extend() syntax
described here:

...with interface types loaded from a classloader other than the JRE
classloader and the main application classloader.

As a simple example, suppose in the main() method of an application, I
create a URL classloader to load arbitrary JAR files containing interface
definitions, and then I create an instance of the Nashorn scripting
engine.  Is it possible to make these types visible to the scripting
engine, such that I could (in a loaded script) use Java.type() then
Java.extend() to create an implementation of such a dynamically-loaded
interface, and return it from the script when invoking a given function?

I'm guessing that it's not possible, because I've not seen this documented
anywhere.  I would assume that it might be possible via the "context
classloader" of the current thread, but I'd prefer not to rely on
undocumented features (supposing that it's the case).  The most flexible
approach would be to pass a classloader (or a map/array of classloaders)
into the binding, and pass it as a second parameter to the Java.type()
function (especially if in a more complicated example, multiple URL
classloaders were loaded and defined types with the same fully-qualified

Additional question #1: would the implementation of the interface in
Nashorn require that I implement default methods, or could they be invoked
in the script without defining them?

Additional question #2: how should resources added to a binding, and more
generally, resources used by a ScriptEngine instance, be cleaned up when
the engine instance is no longer required?  For example, if adding
classloaders is (or can be made) possible, I can't see any way to
explicitly "close" the script engine... I'm assuming the only way to clean
things up is to de-reference the engine and wait for it to be


More information about the nashorn-dev mailing list