I got the same results while developing a mod in which one can use javascript to interact through a block with the world.
The problem is that the JRE jars are not in the class path at runtime.
One can test this with a few lines of code inside the mods constructor or preInit (etc.) method:
URLClassLoader systemClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
URL[] urls = systemClassLoader.getURLs();
for (URL item : urls) {
System.out.println(item.toString());
}
This prints all the paths to the necessary jar files (like nashorn.jar, located in ${JAVA_HOME}jre/libs/ext) into the stdout.
Within IntelliJ Idea (via GradleStart) everything is fine and the class path is intact.
However, running a minecraft forge server, only the jars located in the mods folder are in the class path. The "why" is a miracle to me..
A workaround is to just fix the class path via reflection:
try {
String javaHomeDir = System.getenv("JAVA_HOME");
if (StringUtils.isNullOrEmpty(javaHomeDir)) {
System.out.println("Unable to add java jars to the system class loader: JAVA_HOME is not set.");
} else {
if (!javaHomeDir.endsWith("/")) {
javaHomeDir += "/";
}
File javaLibraryFolder = new File(javaHomeDir + "jre/lib");
Collection<File> jarFiles = FileUtils.listFiles(javaLibraryFolder, new String[]{"jar"}, true);
URLClassLoader systemClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{ URL.class });
// This might fail if a security manager is active
method.setAccessible(true);
for (File jarFile : jarFiles) {
System.out.println("Adding " + jarFile + " to system class loader.");
method.invoke(systemClassLoader, new Object[] { jarFile.toURI().toURL() });
}
}
} catch (Throwable ex) {
throw new RuntimeException("Unable to add java libraries from java home to system class loader: " + ex.getMessage(), ex);
}
After adding them back, one can use the nashorn specific classes again.
Edit: Made a mistake, this does not work. Reporting back if a solution has been found.
Edit 2: Found a workaround. Put a symlink to the "nashorn.jar" into the "mods" folder:
// Linux
ln -s ${JAVA_HOME}/jre/lib/ext/nashorn.jar nashorn.jar
// Windows
mklink nashorn.jar "C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\nashorn.jar"
P.S.: Using the argument "-cp" or setting the environment variable "CLASSPATH" does not seem to have any effect.