在从 IBM Java 7 更新到 8 之前,以下代码用于在 Equinox OSGi 环境中工作:
ScriptEngineManager manager = new ScriptEngineManager(getClass().getClassLoader());
ScriptEngine engine = manager.getScriptEngineManager().getEngineByExtension("js");
engine.eval("<... js code ...>");
((Invocable) engine).getInterface(MyInterface.class) // ECMAScript exception
在之前的设置中,我使用 Rhino 作为引擎,它现在不再注册为可用的 ScriptEngineFactory,但仍在类路径中,只有“Oracle Nashorn”。
更新到 IBM Java 8(包括 Nashorn)后,出现以下异常:
ECMAScript Exception: TypeError: Can not find a common class loader for ScriptObject and MyInterface.
at jdk.nashorn.internal.runtime.ECMAErrors.error(ECMAErrors.java:69)
at jdk.nashorn.internal.runtime.ECMAErrors.typeError(ECMAErrors.java:225)
at jdk.nashorn.internal.runtime.ECMAErrors.typeError(ECMAErrors.java:197)
at jdk.nashorn.internal.runtime.ECMAErrors.typeError(ECMAErrors.java:184)
at jdk.nashorn.internal.runtime.linker.AdaptationResult.typeError(AdaptationResult.java:82)
at jdk.nashorn.internal.runtime.linker.JavaAdapterFactory$AdapterInfo.getAdapterClass(JavaAdapterFactory.java:326)
at jdk.nashorn.internal.runtime.linker.JavaAdapterFactory.getAdapterClassFor(JavaAdapterFactory.java:162)
at jdk.nashorn.internal.runtime.linker.JavaAdapterFactory.getAdapterClassFor(JavaAdapterFactory.java:148)
at jdk.nashorn.internal.runtime.linker.JavaAdapterFactory.getConstructor(JavaAdapterFactory.java:202)
at jdk.nashorn.api.scripting.NashornScriptEngine.getInterfaceInner(NashornScriptEngine.java:291)
at jdk.nashorn.api.scripting.NashornScriptEngine.getInterface(NashornScriptEngine.java:216)
...
Nashorn 尝试通过以下方式检查 jdk.nashorn.internal.runtime.ScriptFunction (Ext ClassLoader) 的类加载器是否可以加载给定的接口 (Bundle ClassLoader),反之亦然:
Class.forName(classBName, false, clazzA.getLoader()) == classB;
任何想法如何配置 OSGi 以让其中一个类加载器看到在 Java 8 + OSGi 上使用 Nashorn 的其他或其他解决方法?