Set Delegate for the Groovy Script With BaseScript

时间:2016-02-12 20:24:17

标签: groovy

I have a following piece of code in my application that runs scripts

return

It worked for Groovy scripts until I started refactoring some of the functionality into the CompilerConfiguration compilerConfiguration = new CompilerConfiguration(); compilerConfiguration.setScriptBaseClass(DelegatingScript.class.getName()); GroovyShell shell = new GroovyShell(compilerConfiguration); try { String scriptText = ""; try (Scanner scanner = new Scanner(resources[0].getInputStream())){ scriptText = scanner.useDelimiter("\\A").next(); } DelegatingScript script = (DelegatingScript)shell.parse(scriptText); script.setDelegate(this.getDelegate()); script.run(); } catch (IOException e) { throw new IllegalArgumentException("Cannot read script resource: '" + filename + "': " + e.getLocalizedMessage(), e); } class. So, for instance I have this Groovy class

@BaseScript

Then I have script

package com.example.scripts

abstract class MyBaseScriptClass extends Script {
    int getTheMeaningOfLife() { 42 }
}

It fails to run with error:

package scripts

import com.example.scripts.MyBaseScriptClass
import groovy.transform.BaseScript

@BaseScript MyBaseScriptClass baseScript

add(context.application, 'test', theMeaningOfLife )

That is if I use Caused by: java.lang.ClassCastException: scripts.Script1 cannot be cast to groovy.util.DelegatingScript at com.metlife.harmony.scripts.groovy.dsl.RunScript.call(RunScript.java:86) ~[classes/:?] in my class it fails to cast it to @BaseScript ? Is there some work around that ?

1 个答案:

答案 0 :(得分:0)

In order to summarize the comments :

IsType2nd(b) && b->IsType2nd(this) override @BaseScript. MyBaseScriptClass didn't extends DelegatingScript, so the cast in RunScript fail.

To fix this error, you should change MyBaseScript to extends DelegatingScript.

setScriptBaseClass(DelegatingScript.class.getName())

If you want to bypass the DelegatingScript, you should maybe check is script is an instanceof DelegatingScript ? If yes, set the delegate, if no, do nothing ?

Inside the script, you can try to change your delegate, but it will work only if the current delegate didn't override the abstract class MyBaseScriptClass extends DelegatingScript { int getTheMeaningOfLife() { 42 } } property :

baseScript