-->

Debugging Groovy scripts running in a ScriptEngine

2019-02-22 08:42发布

问题:

I have a Groovy script which is run like this:

File scriptFile = ...;
ScriptEngine engine = ...;
String script = FileUtils.readFileToString(scriptFile);
Object evalResult = engine.eval(script, bindings);

Unsurprisingly, breakpoint set in the script file doesn't trigger. What can I change to make it work? The script needs to be run in the context of the larger program (no separate launch configuration), and through a ScriptEngine, and the file is only known at runtime.

回答1:

I'm using this hack: I've defined a Java class Debugger which looks like this:

public class Debugger {

    private static final Logger log = LoggerFactory.getLogger( Debugger.class );

    /**
     * Invoke this method anywhere to end up in the Java debugger.
     * 
     * <p>Sometimes, you have code that might eventually be executed or you have a place
     * where you want to stop but no code line.
     * 
     * <p>In these case, use this method.
     * 
     * <p>Don't forget to set a breakpoint, first :-)
     * */
    public static void stopInDebugger() {
        log.error( "Please set a breakpoint in Debugger.stopInDebugger() and try again whatever you just did!" );
    }
}

I have a breakpoint in the log.error line in Ecipse.

Now, I can put this line into the script where I want a breakpoint:

Debugger.stopInDebugger();

Granted, it doesn't allow me to easily step through the script but it's better than nothing.



回答2:

Is your script file in a source folder on the classpath (sounds like it's not)? If not, make it so. You can also change your preferences to ensure that the script file is never compiled by the compiler (and optionally not even copied to the output folder). Go to Preferences -> Groovy -> Compiler and look at script folders to make this happen.