Groovy DSL获取匿名字符串赋值

时间:2014-10-07 17:52:18

标签: groovy dsl

我的DSL看起来像这样:

aMethod {
    "a name"
    "another name"
    "and a third name"
}

我的问题是我无法访问这三个字符串,因为调用闭包只返回最后一个语句。我试图覆盖在发生匿名String语句时调用的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"

不幸的是它不起作用,我认为它很复杂。

1 个答案:

答案 0 :(得分:0)

感谢您的评论。实际上,没有引号定义所有内容会很棒。但是:在拥有可以转换为java对象的dsl后,我很乐意在开发时使用我的语言添加其他注释。我想注释重复的名称等等。 IDE我知道的更好,Intellij和Eclipse将Strings“一个名字”称为一个PSI-Elements。分裂这些元素可能非常不方便......我想。我认为像aMethod {a name}这样的闭包中的语句会产生类似aMethod {a.name}的解释。这意味着我没有StringLiteral Psi“一个名字”,而是拥有一个Object-Psi和一个MethodCall-Psi或类似的东西。我不知道,我的下一个目标是“解析/创建”我的java对象。你确定不可能覆盖String-Constructor吗?

当你有一个包含这个内容的groovy脚本时,是否有任何构造函数被调用:

"hello World"  
相关问题