user9620181
user9620181

Reputation:

Trying to set an object to true or false using a variable in java

So I am refactoring some very old code, and I see the same code repeated about 20 times the only difference is that the object being set to true or false is changing.

I'm trying to figure out how to set the object using .notation to set it to true or false.

it looks something like this.

if("true".equals(this.element.getText())) {
    endorse.setFDSC(true);
}else {
    endorse.setFDSC(false);
}

my current method looks like this.

private void setEndorsmentRecordsToF( EndorsementRecordApplication endorse, String location) throws Exception {

     if("true".equals(this.element.getText())) {
         endorse.setFDSC(true);
     }else {
         endorse.setFDSC(false);
     }
}

Any tips or advice would be greatly appreciated, each one of these objects are different but the same logic applies.

Upvotes: 1

Views: 1501

Answers (1)

drowny
drowny

Reputation: 2147

You can use static methods of Boolean.class. So you can use Boolean.parseBoolean method. And then your code will be like this;

private void setEndorsmentRecordsToF(EndorsementRecordApplication endorse, String location) throws Exception {
    endorse.setFDSC(Boolean.parseBoolean(this.element.getText()));
}

In Boolean.class this methods body is ;

public static boolean parseBoolean(String var0) {
    return var0 != null && var0.equalsIgnoreCase("true");
} 

So checking with equalsIgnoreCase.

If you want to convert boolean value to String , use this method already defined in Boolean.class;

public static String toString(boolean var0) {
    return var0 ? "true" : "false";
}

Upvotes: 2

Related Questions