什么是反映实例方法的惯用Groovy方法?

时间:2011-04-05 18:22:22

标签: reflection groovy

以下是问题的一些示例代码

class Foo {
  String a()
  String b()
}

Bar的初始版本

class Bar {
  List<Foo> foos = new ArrayList<Foo>()

  String getAs() {
    def builder = new StringBuilder()

    foos.each {
        builder.append it.a()
        builder.append System.getProperty("line.separator")
    }

    builder.toString()
  }

  String getBs() {
    def builder = new StringBuilder()

    foos.each {
        builder.append it.b()
        builder.append System.getProperty("line.separator")
    }

    builder.toString()
  }
}

很明显我想重构这个。我目前有这个:

class Bar {
  List<Foo> foos = new ArrayList<Foo>()

  String getAs() {
    collectSections "a"
  }

  String getBs() {
    collectSections "b"
  }

  private String collectSections(String method) {
    def builder = new StringBuilder()

    foos.each {
        builder.append it."${method}"()
        builder.append System.getProperty("line.separator")
    }

    builder.toString()
  }
}

这是最好的常规方法吗?

1 个答案:

答案 0 :(得分:1)

我会这样做,因为它抽象了收集算法并使用标准的Groovy集合操作方法。

class Bar {
  List<Foo> foos = new ArrayList<Foo>()

  String collect(values) {
    values.inject(new StringBuilder()) { b, val ->
        b << val + System.getProperty("line.separator")
    }.toString()
  }

  String getAs() {
    collect foos*.a()
  }

  String getBs() {
    collect foos*.b()
  }
}
相关问题