anish
anish

Reputation: 7412

Using GroovyClassLoader GroovyScriptEngine both

How can i make effective use of GroovyClassLoader GroovyScriptEngine both in a programe

Upvotes: 0

Views: 905

Answers (1)

anish
anish

Reputation: 7412

 class testScriptEngine 
    {
    private final Map<String, CompiledScript> compiledScripts = new HashMap<String, CompiledScript>();
    GroovyClassLoader gcl = new GroovyClassLoader();
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("groovy");
        GroovyCompiledScript compilescript(ScriptEngine engine, String scriptName) {
                GroovyScriptEngineImpl groovyEngineImpl = (GroovyScriptEngineImpl) engine;
                gcl = groovyEngineImpl.getClassLoader();
                Class<?> scriptClass = null;
                try {
                    scriptClass = gcl.parseClass(new File(scriptName));
                    GroovyCompiledScript compiledScript = new GroovyCompiledScript(
                            groovyEngineImpl, scriptClass);
                    return compiledScript;
                } catch (MultipleCompilationErrorsException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (CompilationFailedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return null;
            }
    public void run() {
            // System.out.println(compiledScripts);
            System.out.println(engine instanceof GroovyScriptEngineImpl);
            Bindings bindings = engine.createBindings();
            bindings.putAll(engine.getBindings(ScriptContext.ENGINE_SCOPE));
            String fileName = "script1.groovy";
            CompiledScript compiledScript = compiledScripts.get(fileName);
            try {
                compiledScript.eval(bindings);
            } catch (ScriptException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
private void compileScript() {
        String fileName = "Script1.groovy";
        compiledScripts.put(fileName, compilescript(engine, fileName));
        fileName = "Script2.groovy";
        compiledScripts.put(fileName, compilescript(engine, fileName));
        fileName = "Script3.groovy";
        compiledScripts.put(fileName, compilescript(engine, fileName));

    }
    }

Upvotes: 1

Related Questions