2011-11-12 6 views
0

は、どのように私はあなたが解決しようとしているどのような問題programeは両方

+2

にGroovyClassLoader GroovyScriptEngineの両方を有効に活用することができますか?何を試しましたか?何がうまくいかない?これは本当にそれが立つように問題ではありません。 – OverZealous

+1

私はサーバーを持って、javaで書かれているサーバーは、groovyスクリプトをアップロードするflexiblityを与え、アップロードされたgroovyスクリプトはアップロード時に与えられたgroovyスクリプトがコンパイルする必要があります。 。 groovyスクリプトは、このシナリオ中に他のGroovyスクリプトとの依存関係を含むことができるので、GroovyClassloaderとgroovyScriptEngineの両方を使用します。 – anish

+0

実際の問題文http://stackoverflow.com/questions/8106082/compiling-a-groovy-scripts-that私はGroovyClassloaderを拡張し、loadclassメソッドをオーバーライドしたい – anish

答えて

1
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)); 

    } 
    }