复杂对象prblm stateme2的groovy闭包

时间:2011-09-20 09:25:57

标签: java groovy dsl

我有一个java界面

    public interface IPerson {
      Person  addPerson(String name );
      Person  addPerson(String name1,String name2);
      Person  addPerson(String name,String[] details);
      Person  addPerson(String name,String name1,String[] details);
      Person  addPerson(String name,List<String> details);
    }

PersonImpl .java为:

class PersonImpl implemets Iperson {
       ..
  // and interface methods implemtation

}

,我的person.java看起来像

class Person {
    def firstName;
    def lastName;
}

我的PersonTest.groovy看起来像

def PersonImpl   person  = new PersonImpl();

person.addPerson("anish")
person.addPerson("anish","nath")
person.addPerson("john","smith")
person.addPerson("tim","yates")
def list=[];
list.add("abc")
list.add("qpr")
person.addPerson("anish",list)
person.addPerson("nath","11", [".docsDevNmAccessStatus.1", "Integer", "4"])
person.addPerson("nath","11", [".docsDevNmAccessStatus.1", "String", "4"])

有没有办法为这个界面定义DSL,这样我很容易轻松调用addOperation?

问题是IPerson界面无法更改。

我怎么能写像

这样的dsl
addPerson "anihs" "nath" //call to person.addPerson("anish","nath")
addPerson "tim" "kates" 

//simlary of other interface method any suggestion

1 个答案:

答案 0 :(得分:0)

在Groovy中,addPerson "anihs" "nath"之类的内容并不是真正允许的。如果你想要两个参数,你必须使用逗号。所以你能得到的最好的是addPerson "anihs", "nath"。但这种方法调用只是悬在空中,缺少上下文。一个非常简单的版本当然是:

def PersonImpl person = new PersonImpl();
person.with {
  addPerson "anish"
  addPerson "anish","nath"
  addPerson "john","smith"
  addPerson "tim","yates"
  def list = ["abc", "qpr"]
  addPerson "anish",list
  addPerson "nath","11", [".docsDevNmAccessStatus.1", "Integer", "4"]
  addPerson "nath","11", [".docsDevNmAccessStatus.1", "String", "4"]
}

虽然我不确定这对你来说已经足够了。