Groovy scripts: how to import another groovy file?

If anyone is still looking for a solution (that does not involve writing your whole script as a string):

conf/automation/jsr223/lib.groovy:

import org.slf4j.LoggerFactory

class TestLib {
    static LOG = LoggerFactory.getLogger("org.openhab.core.automation.lib")

    static def testMethod() {
        LOG.info("in TestLib.testMethod")
    }
}

conf/automation/jsr223/foo.groovy:

import org.slf4j.LoggerFactory

LOG = LoggerFactory.getLogger("org.openhab.core.automation.foo")

Class TestLib = this.class.classLoader.parseClass(new File('../conf/automation/jsr223/lib.groovy'))

LOG.info("in main script")
TestLib.testMethod()

Output when the script is loaded:

 [DEBUG] [rt.internal.loader.ScriptFileWatcher] - Dequeued file:/openhab/conf/automation/jsr223/foo.groovy
 [INFO ] [rt.internal.loader.ScriptFileWatcher] - Loading script '/openhab/conf/automation/jsr223/foo.groovy'
 [DEBUG] [ipt.internal.ScriptEngineManagerImpl] - Added ScriptEngine for language 'groovy' with identifier: file:/openhab/conf/automation/jsr223/foo.groovy
 [INFO ] [org.openhab.core.automation.foo     ] - in main script
 [INFO ] [org.openhab.core.automation.lib     ] - in TestLib.testMethod
 [DEBUG] [rt.internal.loader.ScriptFileWatcher] - Script loaded: /openhab/conf/automation/jsr223/foo.groovy

Only thing to note is that the library file should be a class. The methods don’t have to be static, you can do var t = TestClass.newInstance() and call member methods on that.

ref: Load script from groovy script - Stack Overflow

2 Likes