【发布时间】:2025-12-17 21:25:03
【问题描述】:
我有一堆这样的条目:
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 中遇到的问题,是否有一个优雅的解决方案?
【问题讨论】: