尝试使用java中的变量将对象设置为true或false

问题描述 投票:0回答:1

所以我正在重构一些非常古老的代码,我看到相同的代码重复了大约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);
     }
}

任何提示或建议将不胜感激,这些对象中的每一个都是不同的,但同样的逻辑适用。

java object boolean
1个回答
2
投票

你可以使用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检查。

如果要将布尔值转换为String,请使用已在Boolean.class中定义的此方法;

public static String toString(boolean var0) {
    return var0 ? "true" : "false";
}
© www.soinside.com 2019 - 2024. All rights reserved.