Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a groovy script inherit from a Java or Groovy superclass?

Tags:

java

groovy

Here is the script (Scccc.groovy):

import scriptParents.ScriptGroovyParent

println(queryThisBaby("my query"));

and here is the superclass:

class ScriptGroovyParent {

    public ScriptGroovyParent() {
        // TODO Auto-generated constructor stub
    }

//  public String queryThisBaby(String query){
//      
//      return query +" was run.";
//  }

    def queryThisBaby(name) {
        return name +" was run."
    }
}

I get an error though when trying to run the script.

Caught: groovy.lang.MissingMethodException: No signature of method: scripts.Scccc.queryThisBaby() is applicable for argument types: (java.lang.String) values: [my query]
groovy.lang.MissingMethodException: No signature of method: scripts.Scccc.queryThisBaby() is applicable for argument types: (java.lang.String) values: [my query]
    at scripts.Scccc.run(Scccc.groovy:5)

How can this be?

like image 920
Alexander Mills Avatar asked Oct 20 '22 23:10

Alexander Mills


1 Answers

A script can extend a base class using CompilerConfiguration. The caveat here is that base class has to extend Script as groovy scripts extend Script normally and you cannot have multiple inheritance in a "IS A" relationship.

//ScriptGroovyParent.groovy
abstract class ScriptGroovyParent extends Script{
    def queryThisBaby(name) {
        return name +" was run."
    }
}


//Script Scccc.groovy
import org.codehaus.groovy.control.CompilerConfiguration

def configuration = new CompilerConfiguration()
configuration.setScriptBaseClass("ScriptGroovyParent")

def shell = new GroovyShell(this.class.classLoader, new Binding(), configuration)

assert shell.evaluate("queryThisBaby('My Query')") == 'My Query was run.'

You can import the package if they both reside in different packages.

like image 52
dmahapatro Avatar answered Oct 28 '22 23:10

dmahapatro