位运算的运用-权限控制:add,query,modify,del

位运算的运用-权限控制:add,query,modify,del

public class Permission {

    private static final int ALLOW_SELECT = 1<<0;//0001
    private static final int ALLOW_INSERT = 1<<1;//0010
    private static final int ALLOW_UPDATE = 1<<2;//0100
    private static final int ALLOW_DELETE = 1<<3;//1000

    //当前的权限状态
    private int flag;

    public void setPermission(int permission){
        flag = permission;
    }


    /*增加权限,可以一项或者多项*/
    public void addPermission(int permission){
        flag = flag|permission;
    }

    /*删除权限,可以一项或者多项*/
    public void disablePermission(int permission){
        flag = flag&~permission;
    }

    /*是否拥有某些权限*/
    public boolean isAllowed(int permission){
        return (flag&permission)==permission;
    }

    /*是否不拥有某些权限*/
    public boolean isNotAllowed(int permission){
        return (flag&permission)==0;
    }


    public static void main(String[] args) {
		int flag = 15;//1111
		Permission permission = new Permission();
		permission.setPermission(flag);
		permission.disablePermission(ALLOW_DELETE|ALLOW_INSERT);
		System.out.println("ALLOW_SELECT="+permission.isAllowed(ALLOW_SELECT));
		System.out.println("ALLOW_INSERT="+permission.isAllowed(ALLOW_INSERT));
		System.out.println("ALLOW_UPDATE="+permission.isAllowed(ALLOW_UPDATE));
		System.out.println("ALLOW_DELETE="+permission.isAllowed(ALLOW_DELETE));
	}
}

结果:

ALLOW_SELECT=true
ALLOW_INSERT=false
ALLOW_UPDATE=true
ALLOW_DELETE=false

jdk里的NIO里的OP_WRITE、OP_READ等也是用的这种思想。

©️2020 CSDN 皮肤主题: 岁月 设计师: pinMode 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值