同志们,你们好。我有一个问题。
我有两个完全重复的方法,除了它们正在访问不同的字段。我无法将字段值作为参数传递,因为访问发生在循环内(简化示例):
public final class Thing {
ImmutableList<Box> boxes;
public int getNumberOfApples() {
int total = 0;
for (Box box : boxes) {
total += box.getApplesCount();
}
return total;
}
public int getNumberOfPears() {
int total = 0;
for (Box box : boxes) {
total += box.getPearsCount();
}
return total;
}
}
我可以将我的水果放入 map 并将字段名称作为参数传递,但它看起来很脏,我对当前的类组成非常满意。所以问题是 - 我如何重构我的代码以具有单一类型的方法:
public int getNumberOfFruit(SomethingMagic) {
moreMagic;
return total;
}
干杯。
最佳答案
嗯,你可以有这样的东西:
public interface Function<In, Out> {
Out apply(In input);
}
然后:
public int getCount(Function<Box, Integer> projection) {
int total = 0;
for (Box box : boxes) {
total += projection(box);
}
return total;
}
目前构建该投影将是丑陋的,例如
int pears = thing.getCount(new Function<Box, Integer>() {
@Override public Integer apply(Box input) {
return box.getPearsCount();
}
});
但在 Java 8 中,使用 lambda 表达式会简单得多:
int pears = thing.getCount(box -> box.getPearsCount());
请注意,Raffaele Rossi 的回答比我的回答稍微具体一些,方法是使界面变得非通用。这意味着它可以更有效率,因为不需要装箱计数 - 当然,可重用性较低。您决定使用哪种方法是一种判断,这在很大程度上取决于您的实际用例。
关于java - 提供字段访问器方法作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21134795/