简体   繁体   English

实例化groovy类的正确方法

[英]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 : 我的首选是使用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 : 第二种选择是使用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. 两者都可以正常运行,我更喜欢使用GroovyShell,因为我在当前代码中到处都使用它,但是我不知道脚本中的new Foo()是否会导致内存泄漏。 Is it possible? 可能吗?

GroovyShell uses the default GroovyClassLoader. GroovyShell使用默认的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. 因此,如果您不需要GroovyClassLoader提供的任何其他特定功能,则应坚持使用GroovyShell使其保持简单。 GroovyShell and GroovyClassLoader are instances of garbage collected and I don't believe there are memory leaks for neither of them. GroovyShell和GroovyClassLoader是收集的垃圾的实例,我不认为这两个实例都存在内存泄漏。

After @ daggett's help i managed to find the solution that fits my needs. 在@ daggett的帮助下,我设法找到了适合我需要的解决方案。

I will not use groovy classes at all. 我根本不会使用groovy类。

A simple example 一个简单的例子

utility groovy script : 实用groovy脚本:

String doStuff() {
    return "doStuff";
}

String doStuff2(){
    return "doStuff2";
}

calling the utility methods from the main groovy script 从主要的Groovy脚本调用实用程序方法

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. 这不是原始问题的答案,但是由于它适合我的需求,所以我很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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