【发布时间】:2023-03-31 20:50:01
【问题描述】:
我有一个如下所示的 DSL:
aMethod {
"a name"
"another name"
"and a third name"
}
我的问题是我无法访问这三个字符串,因为调用闭包只返回最后一条语句。我试图重写 String(char[] value) 的构造函数,它在发生匿名字符串语句时被调用:
def original
// primitive way to get the String(char[])-constructor
String.class.constructors.each {
if(it.toString() == "public java.lang.String(char[])") {
original = it
}
}
// overriding the constructor
String.metaClass.constructor = { char[] value ->
def instance = original.newInstance(value)
// ... do some further stuff with the instance ...
println "Created ${instance}"
instance
}
// teststring to call String(char[] value)
"teststring"
不幸的是,它没有奏效,而且我认为它很复杂。
【问题讨论】:
-
我怀疑这在没有 AST 的情况下是否可行。你能改变DSL吗?将字符串作为参数传递给方法调用可以解决这个问题,或者不将它们视为字符串,而是将它们视为纯代码:
aMethod { a name } -
+1 我想你需要一个 ast
-
我尝试了纯代码的解决方案,但在闭包中我也允许使用字符串参数调用方法,例如:aMethod {forView(another name)}。我认为这种模式是不允许的,我不想混淆它。没关系,我认为有一个明显的解决方案,比如用方法包装闭包的每个语句
-
字符串可以是什么?如果它们是定义明确的集合,您可以使用这些字符串作为方法编写一个类,然后在闭包内调用它们。
-
不,它们没有定义