Java 在将一个对象复制到另一个对象时,如何避免这么多if语句?
我有以下课程:Java 在将一个对象复制到另一个对象时,如何避免这么多if语句?,java,Java,我有以下课程: public class File { @Getter @Setter private String id; @Getter @Setter private String name; @Getter @Setter private int size; @Getter @Setter private String color; ... about 10 more variables } 我有两个这样的例子: File file = new File(); // assu
public class File
{
@Getter
@Setter
private String id;
@Getter
@Setter
private String name;
@Getter
@Setter
private int size;
@Getter
@Setter
private String color;
... about 10 more variables
}
我有两个这样的例子:
File file = new File(); // assume each variable has a value initialized
File newFile = new File(); // assume each variable has a value initialized
我想要的逻辑是,如果我的newFile
包含变量的值,我想保留它。否则,我想返回到文件中的原始值
所以我有以下方法:
public void merge(File oldFile, File newFile)
{
if (newFile.getId() != null)
{
oldFile.setId(newFile.getId());
}
if (newFile.getName() != null)
{
oldFile.setName(newFile.getName());
}
if (newFile.getSize() != null)
{
oldFile.setSize(newFile.getSize());
}
if (newFile.getColor() != null)
{
oldFile.setColor(newFile.getColor());
}
... etc
}
如何避免这么多if语句和空检查?我认为代码看起来很难看。您可以在实用程序类中创建合并
函数,该函数接受两个文件对象,并使用反射来完成此操作
static final class FileUtil {
private FileUtil() throws IllegalAccessException {
throw new IllegalAccessException("can not create an object from this class!");
}
public final static void merge(File oldFile, File newFile) throws Exception {
Method[] methods = newFile.getClass().getDeclaredMethods();
for (Method m : methods) {
if (m.getName().contains("get")) {
Object value = m.invoke(newFile);
if (value != null) {
String name = m.getName();
name = name.substring(name.indexOf("get") + 3);
name = "set" + name;
if (value instanceof Integer) {
Method method = oldFile.getClass().getDeclaredMethod(name, int.class);
method.invoke(oldFile, (int) value);
} else {
Method method = oldFile.getClass().getDeclaredMethod(name, value.getClass());
method.invoke(oldFile, value);
}
}
}
}
}
}
如果新值为null,则可以编写默认为旧值的函数,也可以使用预编写的函数,如:
这意味着您的代码变成:
public void merge(File oldFile, File newFile)
{
oldFile.setId(defaultIfNull(newFile.getId(), oldFile.getId());
oldFile.setName(defaultIfNull(newFile.getName(), oldFile.getName());
oldFile.setSize(defaultIfNull(newFile.getSize(), oldFile.getSize());
// etc
}
当然,如果您决定此行为应始终适用于您的文件,则可以将其放在所有setter中,例如:
public void setName(String name) {
this.name = defaultIfNull(name, this.name);
}
然后像平常一样打电话:
public void merge(File oldFile, File newFile)
{
oldFile.setId(newFile.getId());
oldFile.setName(newFile.getName());
// etc
}
为什么需要空检查?如果允许空值,只需复制空值。如果为空,则意味着我要回退到旧文件值是什么,我不想将其替换为空值。请参阅我的评论“我想要的逻辑是,如果我的新文件包含变量的值,我想保留它。否则,我想退回到文件对象中我的原始值。”你使用lombok吗?@sc0der是的,我也在查看一个名为ModelMapper的库,我想知道这在这里是否有用。这是否回答了你的问题?defaultIfNull不坏。。。我只是觉得回退并调用一个具有相同值的setter(它已经设置好了,就好像新值为null一样)有点奇怪,我认为最好不要调用setter,这取决于您如何定义“怪异”和“更好”:。我认为我提到的两种形式都比问题中缩进的if
块“更好”,这两种形式也是我在工作中看到的常见做法。