我正在创建一个名为 setState 的方法,我想为其使用二元运算符,但我想创建一些东西来检查传递的参数是否是类中定义的常量:
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;
}
}
因此,当我输入 setState(10, false) 时,它会显示:错误的参数类型,找到 x,需要 y
最佳答案
您只希望 stateType 为 STATE1、STATE2 或 STATE3 之一? 您可以使用该类中定义的枚举。类似于:
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;
}
}
}
关于java - 如何设置方法所需的常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34474575/