所以我正在重构一些非常旧的代码,我看到相同的代码重复了大约 20 次,唯一的区别是设置为 true 或 false 的对象正在改变。
我试图弄清楚如何使用 .notation 设置对象以将其设置为 true 或 false。
它看起来像这样。
if("true".equals(this.element.getText())) {
endorse.setFDSC(true);
}else {
endorse.setFDSC(false);
}
我当前的方法如下所示。
private void setEndorsmentRecordsToF( EndorsementRecordApplication endorse, String location) throws Exception {
if("true".equals(this.element.getText())) {
endorse.setFDSC(true);
}else {
endorse.setFDSC(false);
}
}
任何提示或建议将不胜感激,每个对象都是不同的,但适用相同的逻辑。
最佳答案
您可以使用Boolean.class
的静态方法。所以你可以使用 Boolean.parseBoolean
方法。然后你的代码将是这样的;
private void setEndorsmentRecordsToF(EndorsementRecordApplication endorse, String location) throws Exception {
endorse.setFDSC(Boolean.parseBoolean(this.element.getText()));
}
在 Boolean.class
中,该方法主体是;
public static boolean parseBoolean(String var0) {
return var0 != null && var0.equalsIgnoreCase("true");
}
因此请使用equalsIgnoreCase进行检查。
如果您想将 boolean 值转换为字符串,请使用Boolean.class
中已定义的此方法;
public static String toString(boolean var0) {
return var0 ? "true" : "false";
}
关于java - 尝试使用 java 中的变量将对象设置为 true 或 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52262624/