简体   繁体   中英

Correct way to instantiate a groovy class

I want to instatiate a groovy class and i have some concerns

My first choice is to use GroovyShell :

groovy-script:

class Foo {
    public String doStuff(String stuff) {
        return stuff + "_utils";
    }
}
new Foo(); // ??

main-script :

GroovyShell shell = new GroovyShell();
Script script = shell.parse(new File(path));
def clazz = script.run();
String result = clazz.doStuff("test");
print(result); // test_utils;

The second option is to use GroovyClassLoader :

groovy-script

class Foo {
    public String doStuff(String stuff) {
        return stuff + "_utils";
    }
}

main-script

GroovyClassLoader loader = new GroovyClassLoader();
Script script = loader.parseClass(new File(path))
Object clazz = script.newInstance();
Object[] args = new Object[1];
args[0] = "test";
String result = clazz.invokeMethod("doStuff", args);
print(result) // test_utils

Both will run fine, i would prefer to use GroovyShell because i use it everywhere in my current code, but i don't know if new Foo() inside my scripts can cause any memory leaks. Is it possible?

GroovyShell uses the default GroovyClassLoader. So if you don't need any extra specific features that are provided by GroovyClassLoader, you should stick to GroovyShell to keep it simple. GroovyShell and GroovyClassLoader are instances of garbage collected and I don't believe there are memory leaks for neither of them.

After @ daggett's help i managed to find the solution that fits my needs.

I will not use groovy classes at all.

A simple example

utility groovy script :

String doStuff() {
    return "doStuff";
}

String doStuff2(){
    return "doStuff2";
}

calling the utility methods from the main groovy script

GroovyShell shell = new GroovyShell();
Script utilsScript = shell.parse(new File(PATH_TO_UTIL_SCRIPT));
String result = utilsScript.doStuff();
println(result); // doStuff;
String result2 = utilsScript.doStuff2();
println(result2); // doStuff2;

This is not the answer to the original question but since it fits my need i am fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM