【发布时间】:2016-04-21 13:43:19
【问题描述】:
我想知道如何在运行时从 Java 应用程序中创建一个 Closure 对象,其中闭包的内容是事先不知道的。我找到了一个解决方案,但我怀疑它是最优的。
背景:我已经编写了一些解析领域特定语言的 Groovy 代码。解析代码被静态编译并包含在 Java 应用程序中。在解析器实现中,我有充当 DSL 特定部分的代表的类。这些类使用以下模式调用:
class DslDelegate {
private Configuration configuration
def section(@DelegatesTo(SectionDelegate) Closure cl) {
cl.delegate = new SectionDelegate(configuration)
cl.resolveStrategy = Closure.DELEGATE_FIRST
cl()
}
}
我希望直接从 Java 代码中调用这样的方法。我能够创建一个新的DslDelegate 对象,然后调用section() 方法。但是,我需要创建并传递一个作为Closure 实例的参数。我希望从 String 对象初始化内容。
我的解决方案: 以下 Java 代码(实用程序)正在运行,但我要求改进。这肯定可以以更清洁或更有效的方式完成吗?
/**
* Build a Groovy Closure dynamically
*
* @param strings
* an array of strings for the text of the Closure
* @return a Groovy Closure comprising the specified text from {@code strings}
* @throws IOException
*/
public Closure<?> buildClosure(String... strings) throws IOException {
Closure<?> closure = null;
// Create a method returning a closure
StringBuilder sb = new StringBuilder("def closure() { { script -> ");
sb.append(String.join("\n", strings));
sb.append(" } }");
// Create an anonymous class for the method
GroovyClassLoader loader = new GroovyClassLoader();
Class<?> groovyClass = loader.parseClass(sb.toString());
try {
// Create an instance of the class
GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();
// Invoke the object's method and thus obtain the closure
closure = (Closure<?>) groovyObject.invokeMethod("closure", null);
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
} finally {
loader.close();
}
return closure;
}
【问题讨论】:
-
好问题。你有没有找到更清洁的解决方案?