开发者

What is the idiomatic Groovy way to reflect an instance method?

Here's some example code for the question

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

Initial version of 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.toStrin开发者_如何学Pythong()
  }
}

So clearly I want to refactor this. I currently have this:

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()
  }
}

Is this the best groovy way to do this?


I would do it this way as it abstracts collection algorithm and uses standard Groovy collection manipulation methods.

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()
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜