Home > Net >  Determine if any boolean flag is true
Determine if any boolean flag is true

Time:10-19

There is a class that is like a structure for flags. I.e. it is comprised of flags.
E.g.

public class Foo { 
  boolean isA;  
  boolean isB;  
  boolean isC;  
  boolean isD;  
  boolean isE;  
  boolean isX;  
  boolean isY;  
}

I need to check at some point if at least one of the flags is true. Besides a series of if statements e.g.

boolean isAnyTrue = false;  
if(foo.isA) isAnyTrue = true; 
else if(foo.isB) isAnyTrue = true;
else if(foo.isC) isAnyTrue = true;
else if(foo.isD) isAnyTrue = true;
else if(foo.isE) isAnyTrue = true;  
else if(foo.isX) isAnyTrue = true;  
else if(foo.isY) isAnyTrue = true;

Or

boolean isAnyTrue = foo.isA || foo.isB || foo.isC || foo.isD || foo.isE || foo.isX || foo.isY;  

Is there any other way to achieve this?

CodePudding user response:

Add isAnyTrue() method to the Foo and check all properties:

public boolean isAnyTrue() {
    return isA || isB || ... || isY;
}

If the number of properties is too big to handle it in this way, you can use Reflection to find all boolean properties and check if any is set to true.

CodePudding user response:

First of all, I think this is a bad way to do things. But none the less since you mentioned that you can't change the code as of now. Maybe you could look into Reflection, which again isn't the most optimized way to do it.

public boolean isTruePresent() throws IllegalAccessException {
    var fields = Foo.class.getDeclaredFields();
    Foo test = new Foo();
    boolean hasTrue = false;

    for(var field : fields) {
        if(field.getType().getSimpleName().equals("boolean")) {
            hasTrue = hasTrue || (boolean) field.get(test);
        }
    }
    return hasTrue;
}
  • Related