Reputation: 23
I am creating a method called setState and I want to use binary operators for it, but I want to create something to check if the passed argument is a constant defined in the class:
public static final int STATE1 = 0b1;
public static final int STATE2 = 0b10;
public static final int STATE3 = 0b100;
public void setState(int stateType, boolean state){
if(state){
this.state |= stateType;
}else{
this.state &= ~stateType;
}
}
So when I type setState(10, false) it will say: Wrong argument type, found x, required y
Upvotes: 0
Views: 62
Reputation: 726479
One way to check a value against a group of allowed values is a Set<Integer>
that contains all the allowed values. You can construct such set in a static constructor of the class, i.e.
private static final Set<Integer> allowedState = new HashSet<Integer>();
static {
allowedState.add(STATE1);
allowedState.add(STATE2);
allowedState.add(STATE3);
}
Now you can check if the state passed to you is valid by verifying that allowedState
contains stateType
:
if (!allowedState.contains(stateType)) {
// Throw an exception
}
To ensure that the allowedState set is immutable use Collcetions.unmodifiableSet()
. Modifier final
only ensures that the reference cannot be redinded to another object.
However, an approach based on raw int
constants is not idiomatic to Java. A better way to achieve the same effect would be wrapping the states in an enum
(tutorial), which would make sure that only a valid constant could be passed to your setState
method:
public enum State {
STATE1(0b1)
, STATE2(0b10)
, STATE3(0b100);
private final int bitMask;
State(int bitMask) { this.bitMask = bitMask; }
public int getBitMask() { return bitMask; }
}
Upvotes: 1
Reputation: 401
you only want stateType to be one of STATE1, STATE2, or STATE3? You could use an enum defined in that class. Something like:
public class MyClass{
public enum State{
STATE1 (0b1),
STATE2(0b10),
STATE3(0b100);
public final int value;
State(int value){
this.value = value;
}
}
public void setState(State stateType, boolean state){
if(state){
this.state |= stateType.value;
}else{
this.state &= ~stateType.value;
}
}
}
Upvotes: 1