Java examples for javax.script:ScriptEngine
create New Script Engine By Language
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.script.ScriptEngine; import javax.script.ScriptEngineFactory; import javax.script.ScriptEngineManager; public class Main{ private static ScriptEngineManager scriptEngineManager; private static final Map<String, List<ScriptEngineFactory>> languageFactoryMap = new HashMap<String, List<ScriptEngineFactory>>(); private static List<ScriptEngineFactory> engineFactories = null; public static ScriptEngine createNewScriptEngineByLanguage( String languageName) { // Defaults to Groovy ScriptEngine scriptEngine = getScriptEngineManager() .getEngineByName("groovy"); if (engineFactories == null) { populateEngineFactoryMap();//from w ww . j a v a 2 s .com } List<ScriptEngineFactory> factories = languageFactoryMap .get(languageName); if (factories != null) { for (ScriptEngineFactory factory : factories) { try { scriptEngine = factory.getScriptEngine(); if (scriptEngine != null) { break; } } catch (Exception e) { // Do nothing, try the next engine } } } return scriptEngine; } public static ScriptEngineManager getScriptEngineManager() { if (scriptEngineManager == null) { System.setProperty("org.jruby.embed.localvariable.behavior", "persistent");// required for JRuby, transparent // for others scriptEngineManager = new ScriptEngineManager( ScriptUtils.class.getClassLoader()); populateEngineFactoryMap(); } return scriptEngineManager; } private static void populateEngineFactoryMap() { engineFactories = getScriptEngineManager().getEngineFactories(); if (engineFactories != null) { for (ScriptEngineFactory factory : engineFactories) { final String languageName = factory.getLanguageName(); List<ScriptEngineFactory> languageFactories = languageFactoryMap .get(languageName); if (languageFactories == null) { languageFactories = new ArrayList<ScriptEngineFactory>(); languageFactoryMap.put(languageName, languageFactories); } languageFactories.add(factory); } } } }