I want to store permissions in a bit set to compare them efficiently in Java. A 1 would mean p开发者_高级运维ermission granted and 0 permission denied. If the authorization is performed the required permissions would be compared to the permission set.
My idea is to use AND and compare the result with the requested permissions.
Example:
0010 1101 Granted Permissions
AND 0000 0101 Requested Permissions
= 0000 0101 Result
if (Result == Requested Permissions)
allow
else
deny
Could that be done more efficient or simple?
I'll focus on the "simple" part, because I don't think that this operation will be a performance bottleneck in any serious application.
You can use a BitSet
which has all the necessary operations.
A more OO-approach and much easier to understand and read would be to represent your permissions with an enum
and to use a EnumSet
. For enums with only a few values it will be about as performant as the BitSet
, because it'll use a very similar implementation.
If you are using Java 5 or later, I recommend using Enum
(s) and an EnumSet
instead. It is much easier to handle and AFAIK performs equally well.
Your approach is perfectly fine and will work as expected. Sure, you could do this in several more complicated ways but I see nothing wrong in using bit manipulation operators if the context fits as it does in your case. After all these operators are part of the Java core language and are not marked as @deprecated or @evil.
精彩评论