java将getter/setter作为方法引用传递
我有一大堆这样的条目:
if (update) {
if (activity.getName() == null) {
logger.debug(" Setting name on " + id);
} else
if (!activity.getName().equals(name)) {
logger.debug(" Updating name on " + id);
}
}
// if (!update) not logged on purpose
activity.setName(name);
if (update) {
if (activity.getPlannedDuration() == null) {
logger.debug(" Setting plannedDuration on " + id);
} else
if (!activity.getPlannedDuration().equals(duration)) {
logger.debug(" Updating plannedDuration on " + id);
}
}
// if (!update) not logged on purpose
activity.setPlannedDuration(duration);
出于代码可读性的目的,我想用如下内容替换它们:
updateField(update, name, "name", activity.getName, activity.setName);
updateField(update, duration, "plannedDuration", activity.getPlannedDuration, activity.setPlannedDuration);
我知道这是一个常见的问题,我做了家庭作业,wraping methods to Callable interface似乎是最简单的解决方案。但是,这个解决方案将比我当前的代码更混乱(记住,我这样做是为了可读性)
那么,有没有优雅的Java解决方案
# 1 楼答案
你可以重构特定的代码:
这不是什么了不起的事,但仍然是一种进步。请注意,无论您是否记录了该字段,当前您实际上都在更新该字段——您确定这是您想要的吗?我更期待的是:
但是,目前在Java中没有传递方法的简单方法。然而,Java8将使方法引用和lambda表达式变得更加简单