Java 中 Enum 枚举类的使用技巧
使用Enum类做配置类
原理:
位运算符
参考:C/Cpp中的位运算符 - htj10 - 博客园 (cnblogs.com)
GoodFeature 类
(从 fastjson-1.2.47.jar 里的 SerializerFeature 学习到的)
package test; /** * 配置类、开关类 * @author John * */ public enum GoodFeature { AFeature,//A BFeature, CFeature; private final int mask; private GoodFeature() { this.mask = (1 << ordinal()); } public final int getMask() { return this.mask; } public static boolean isEnabled(int features, GoodFeature feature) { return (features & feature.getMask()) != 0; } public static boolean isEnabled(int features, int fieaturesB, GoodFeature feature) { int mask = feature.getMask(); return ((features & mask) != 0) || ((fieaturesB & mask) != 0); } /** * 打开或关闭对应的开关(特征) * @param features 原来的开关(特征)(可以从 of() 获得) * @param feature 需要打开或关闭的开关(特征) * @param state true:打开 false:关闭 * @return */ public static int config(int features, GoodFeature feature, boolean state) { if (state) features |= feature.getMask(); else { features &= (feature.getMask() ^ 0xFFFFFFFF); } return features; } public static int of(GoodFeature[] features) { if (features == null) { return 0; } int value = 0; for (GoodFeature feature : features) { value |= feature.getMask(); } return value; } }
测试Demo
private static void test2() { GoodFeature a = GoodFeature.AFeature; GoodFeature b = GoodFeature.BFeature; GoodFeature c = GoodFeature.CFeature; System.out.println(a.ordinal());//0 System.out.println(b.ordinal());//1 System.out.println(c.ordinal());//2 System.out.println(a.getMask());//1 System.out.println(b.getMask());//2 System.out.println(c.getMask());//4 System.out.println("-----------------"); //打开 int c1 = GoodFeature.config(0, a, true); int c2 = GoodFeature.config(c1, b, true); int c3 = GoodFeature.config(c2, c, true); // System.out.println(c3);//7 int abc = GoodFeature.of(new GoodFeature[] { GoodFeature.AFeature,GoodFeature.BFeature,GoodFeature.CFeature }); System.out.println(abc);//7 System.out.println("-----------------"); System.out.println(GoodFeature.isEnabled(c3, GoodFeature.AFeature));//true System.out.println(GoodFeature.isEnabled(c3, GoodFeature.BFeature));//true System.out.println(GoodFeature.isEnabled(c3, GoodFeature.CFeature));//true c3 = GoodFeature.config(c3, GoodFeature.AFeature, false);//关闭A特性 c3 = GoodFeature.config(c3, GoodFeature.BFeature, false);//关闭B特性 System.out.println(GoodFeature.isEnabled(c3, GoodFeature.AFeature));//false System.out.println(GoodFeature.isEnabled(c3, GoodFeature.BFeature));//false System.out.println(GoodFeature.isEnabled(c3, GoodFeature.CFeature));//true }
常记溪亭日暮,沉醉不知归路。兴尽晚回舟,误入藕花深处。争渡,争渡,惊起一滩鸥鹭。
昨夜雨疏风骤,浓睡不消残酒。试问卷帘人,却道海棠依旧。知否?知否?应是绿肥红瘦。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义