原创

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

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://junmoxiao.blog.csdn.net/article/details/98471598

位运算的运用-权限控制: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等也是用的这种思想。

展开阅读全文

没有更多推荐了,返回首页