java判断枚举是否包含_Java:检查枚举是否包含给定的string?

本文介绍了多种检查枚举值是否存在于枚举类型中的方法,包括使用for循环、HashSet、Java 8 Stream API、Apache Commons库等。这些方法适用于不同场景,帮助开发者高效地进行枚举值检查。

这应该做到这一点:

public static boolean contains(String test) { for (Choice c : Choice.values()) { if (c.name().equals(test)) { return true; } } return false; }

这样的方式意味着你不必担心后面添加额外的枚举值,他们都被检查。

编辑:如果枚举非常大,您可以将值粘贴到HashSet中:

public static HashSet getEnums() { HashSet values = new HashSet(); for (Choice c : Choice.values()) { values.add(c.name()); } return values; }

然后你可以做: values.contains("your string") ,返回true或false。

改用Apache commons lang3 lib

EnumUtils.isValidEnum(MyEnum.class, myValue)

你可以使用Enum.valueOf

enum Choices{A1, A2, B1, B2}; public class MainClass { public static void main(String args[]) { Choices day; try { day = Choices.valueOf("A1"); //yes } catch (IllegalArgumentException ex) { //nope } }

如果你希望检查经常失败,你可能会更好的使用一个简单的循环,如其他人所示 – 如果你的枚举包含许多值,可能builda HashSet或类似的枚举值转换为一个string,并查询该HashSet,

番石榴引子可能是你的朋友

像这样:

enum MyData { ONE, TWO } @Test public void test() { if (!Enums.getIfPresent(MyData.class, "THREE").isPresent()) { System.out.println("THREE is not here"); } }

更好:

enum choices { a1, a2, b1, b2; public static boolean contains(String s) { for(choices choice:values()) if (choice.name().equals(s)) return true; return false; } };

如果您正在使用Java 1.8,则可以selectStream + Lambda来实现此目的:

public enum Period { DAILY, WEEKLY }; //This is recommended Arrays.stream(Period.values()).anyMatch((t) -> t.name().equals("DAILY1")); //May throw java.lang.IllegalArgumentException Arrays.stream(Period.values()).anyMatch(Period.valueOf("DAILY")::equals);

我不认为有,但你可以做这样的事情:

enum choices {a1, a2, b1, b2}; public static boolean exists(choices choice) { for(choice aChoice : choices.values()) { if(aChoice == choice) { return true; } } return false; }

编辑:

请参阅理查德的版本,因为这样做更合适,除非您将其转换为使用Richards所使用的string。

如果您使用的是Apache Commons(或者愿意这样做),那么可以使用以下命令来检查它:

ArrayUtils.contains(choices.values(), value)

你可以使用这个

YourEnum {A1,A2,B1,B2}

boolean contains(String str){ return Sets.newHashSet(YourEnum.values()).contains(str); }

将@ wightwulf1944build议的更新结合起来使解决scheme更有效率。

几个假设:

1)没有尝试/捕捉,因为它是特殊的stream量控制

2)“包含”方法必须很快,因为它通常运行几次。

3)空间不限(普通的解决scheme)

import java.util.HashSet; import java.util.Set; enum Choices { a1, a2, b1, b2; private static Set _values = new HashSet<>(); // O(n) - runs once static{ for (Choices choice : Choices.values()) { _values.add(choice.name()); } } // O(1) - runs several times public static boolean contains(String value){ return _values.contains(value); } }

您可以先将枚举转换为列表,然后使用列表包含方法

enum Choices{A1, A2, B1, B2}; List choices = Arrays.asList(Choices.values()); //compare with enum value if(choices.contains(Choices.A1)){ //do something } //compare with String value if(choices.contains(Choices.valueOf("A1"))){ //do something }

如果你想通过string查找,你可以使用valueOf("a1")

为什么不把巴勃罗的答复与valueOf()?

public enum Choices { a1, a2, b1, b2; public static boolean contains(String s) { try { Choices.valueOf(s); return true; } catch (Exception e) { return false; } }

这是一个枚举,那些是不变的值,所以如果它在switch语句中就是这样做的:

case: val1 case: val2

另外为什么你需要知道什么是一个常数声明?

public boolean contains(Choices value) { return EnumSet.allOf(Choices.class).contains(value); }

番石榴更简单:

boolean isPartOfMyEnum(String myString){ return Lists.newArrayList(MyEnum.values().toString()).contains(myString); }

这结合了以前方法的所有方法,并应具有相同的性能。 它可以用于任何枚举,从@Richard H内嵌“编辑”解决scheme,并使用例外作为@bestsss之类的无效值。 唯一的折衷是需要指定类,但是这将变成双线。

import java.util.EnumSet; public class HelloWorld { static enum Choices {a1, a2, b1, b2} public static > boolean contains(Class _enumClass, String value) { try { return EnumSet.allOf(_enumClass).contains(Enum.valueOf(_enumClass, value)); } catch (Exception e) { return false; } } public static void main(String[] args) { for (String value : new String[] {"a1", "a3", null}) { System.out.println(contains(Choices.class, value)); } }

}

com.google.common.collect.Sets.newHashSet(MyEnum.values()).contains("myValue")

这种方法可以用来检查任何Enum ,你可以将它添加到一个Utils类中:

public static > boolean enumContains(Class enumerator, String value) { for (T c : enumerator.getEnumConstants()) { if (c.name().equals(value)) { return true; } } return false; }

这样使用它:

boolean isContained = Utils.enumContains(choices.class, "value");

解决scheme检查值是否存在以及获取枚举值作为回报:

protected TradeType getEnumType(String tradeType) { if (tradeType != null) { if (EnumUtils.isValidEnum(TradeType.class, tradeType)) { return TradeType.valueOf(tradeType); } } return null; }

我的名声不需要评论,但我认为chaiyachaiya和帕布罗圣克鲁斯的答案是完全错误的。 首先,Enum用==操作符覆盖散列码,因为它的实例保证是单例,因此它不会比较操作数的逻辑相等。 这就是为什么如果我们使用MyEnum.values()并检查contains() ,我们将永远是false 。 其次, MyEnum.values().toString()将调用MyEnum类对象的toString() ,而不是MyEnum类的实例(如果在类的cause中覆盖此方法)。 那么,你将得到什么与Lists.newArrayList(MyEnum.values().toString()).contains(myString) ?

enum在Java中非常强大。 你可以很容易地为你的枚举添加一个contains方法(就像你将一个方法添加到一个类中一样):

enum choices { a1, a2, b1, b2; public boolean contains(String s) { if (s.equals("a1") || s.equals("a2") || s.equals("b1") || s.equals("b2")) return true; return false; } };

修改:;from enum import Enum import sys import logging from pathlib import Path # 设置日志 logger = logging.getLogger(__name__) # 添加项目根目录到 Python 路径,确保从core 模块可以正确导入 project_root = Path(__file__).parent.parent if str(project_root) not in sys.path: sys.path.insert(0, str(project_root)) # 使用安全的导入方�? try: from core.ui_config import UI_CONFIG UI_CONFIG_AVAILABLE = True logger.info("成功导入 UI_CONFIG") except ImportError as import_error: # 提供回退实现 logger.warning(f"无法导入 UI_CONFIG: {import_error}, 使用回退实现") UI_CONFIG_AVAILABLE = False # 回退�?UI 配置 class UIConfig: """回退�?UI 配置""" theme = "default" language = "zh_CN" font_size = 12 font_family = "Microsoft YaHei" @classmethod def get(cls, key, default=None): return getattr(cls, key, default) UI_CONFIG = UIConfig() class EventType(Enum): """系统所有事件类型的统一枚举定义(整合版�?"" # ========== 系统级事�?========== SYSTEM_STARTUP = "system_startup" SYSTEM_SHUTDOWN = "system_shutdown" MODULE_READY = "module_ready" MODULE_CLEAR = "module_clear" MODULE_REFRESH = "module_refresh" MODULE_SWITCH = "module_switch" ERROR = "error" TEST_EVENT = "test_event" # ========== 模块控制事件 ========== MODULE_RUN = "module_run" MODULE_COMPLETE = "module_complete" MODULE_SAVE = "module_save" MODULE_RESULT = "module_result" # ========== 数据处理事件 ========== DATA_SUBMIT = "data_submit" DATA_UPDATE = "data_update" DATA_FREEZE = "data_freeze" DATA_ORGANIZE = "data_organize" DATA_RESULT = "data_result" # ========== 分析结果事件 ========== ANALYSIS_RESULT = "analysis_result" INPUT_ANALYSIS_START = "input_analysis_start" INPUT_ANALYSIS_END = "input_analysis_end" COMBINATION_ANALYSIS_START = "combination_analysis_start" COMBINATION_ANALYSIS_END = "combination_analysis_end" COMBINATION_RESULT = "combination_result" FOLLOW_ANALYSIS_START = "follow_analysis_start" FOLLOW_ANALYSIS_END = "follow_analysis_end" FOLLOW_ANALYSIS_UPDATE = "follow_analysis_update" TREND_ANALYSIS_START = "trend_analysis_start" TREND_ANALYSIS_END = "trend_analysis_end" TREND_ANALYSIS_RESULT = "trend_analysis_result" NUMBER_GENERATION_START = "number_generation_start" NUMBER_GENERATION_FINISH = "number_generation_finish" NUMBER_GENERATION_RESULT = "number_generation_result" # ========== UI相关事件 ========== UI_UPDATE = "ui_update" DIALOG_OPEN = "dialog_open" DIALOG_CLOSE = "dialog_close" REGISTER_UI = "register_ui" GET_RESULTS = "get_results" # ========== 状态事�?========== LOADING_PROGRESS = "loading_progress" LOADING_COMPLETE = "loading_complete" # ========== 特定功能事件 ========== EXCLUDE_NUMBERS = "exclude_numbers" POOL_UPDATE = "pool_update" NUMBER_UPDATE = "number_update" # ========== 模块标识事件 ========== INPUT_MODULE = "input_module" COMBINATION_MODULE = "combination_module" FOLLOW_MODULE = "follow_module" TREND_MODULE = "trend_module" GENERATION_MODULE = "generation_module" # ========== 测试事件 ========== DEMO_EVENT = "demo_event" @classmethod def get_value(cls, event_type_obj): """获取事件类型的字符串"" if isinstance(event_type_obj, cls): return event_type_obj.value return event_type_obj @classmethod def from_string(cls, value): """从字符串获取事件类型枚举""" try: # 通过查找枚举成�? for member in cls: if member.value == value: return member raise KeyError(f"未知的事件类型�? {value}") except KeyError: raise ValueError(f"未知的事件类�? {value}") @classmethod def validate_event_type(cls, event_type_string): """验证事件类型字符串是否有�?"" try: # 检查字符串是否存在于枚举? for member in cls: if member.value == event_type_string: return True return False except (KeyError, TypeError): return False @classmethod def validate_and_raise(cls, event_type_string): """验证事件类型并在无效时抛出异�?"" if not cls.validate_event_type(event_type_string): raise ValueError(f'无效事件类型: {event_type_string}') return True @classmethod def get_all_values(cls): """获取所有事件类型的字符串列�?"" return [e.value for e in cls] # 返回字符串列�? @classmethod def is_valid_event_type(cls, value): """检查是否为有效的事件类�?"" try: if isinstance(value, cls): return True # 检查字符串是否存在于枚举? for member in cls: if member.value == value: return True return False except (KeyError, TypeError): return False @classmethod def get_name_from_value(cls, value): """从字符串获取事件类型名�?"" for member in cls: if member.value == value: return member.name return None # 便捷函数 def create_event_type_map(): """创建事件类型到字符串的映射""" return {event_type.name: event_type.value for event_type in EventType} def validate_event_type_string(event_type_string): """验证事件类型字符串的便捷函数""" return EventType.validate_event_type(event_type_string) def validate_event_type_string_with_raise(event_type_string): """验证事件类型字符串并在无效时抛出异常的便捷函�?"" return EventType.validate_and_raise(event_type_string) # 测试代码 if __name__ == "__main__": # 设置日志 logging.basicConfig(level=logging.INFO) # 测试事件类型功能 print("所有事件类�?") for event_type in EventType: print(f" {event_type.name} = {event_type.value}") print(f"\n事件类型数量: {len(EventType)}") # 测试便捷方法 test_event = EventType.TEST_EVENT print(f"\n测试事件: {test_event.name}, �? {test_event.value}") # 测试从字符串获取 try: from_string_result = EventType.from_string("test_event") print(f"从字符串获取: {from_string_result} (名称: {from_string_result.name}, �? {from_string_result.value})") except ValueError as error: print(f"从字符串获取失败: {error}") # 测试有效性检�? test_string = "test_event" print(f"是否为有效事件类�?'{test_string}': {EventType.is_valid_event_type(test_string)}") unknown_string = "UNKNOWN_EVENT" print(f"是否为有效事件类�?'{unknown_string}': {EventType.is_valid_event_type(unknown_string)}") print(f"是否为有效事件类型枚举对�? {EventType.is_valid_event_type(EventType.TEST_EVENT)}") # 测试验证函数 print(f"\n验证函数测试:") print(f"验证 '{test_string}': {validate_event_type_string(test_string)}") print(f"验证 '{unknown_string}': {validate_event_type_string(unknown_string)}") # 测试带异常抛出的验证 try: validate_event_type_string_with_raise(test_string) print(f"验证 '{test_string}' (带异�?: 成功") except ValueError as validation_error: print(f"验证 '{test_string}' (带异�?: 失败 - {validation_error}") try: validate_event_type_string_with_raise(unknown_string) print(f"验证 '{unknown_string}' (带异�?: 成功") except ValueError as validation_error: print(f"验证 '{unknown_string}' (带异�?: 失败 - {validation_error}") # 测试获取所有�? print(f"\n所有事件�? {EventType.get_all_values()}") # 测试名称到的映射 print(f"\n名称到映射示�? {create_event_type_map()['TEST_EVENT']}") __all__ = ['EventType', 'UI_CONFIG', 'create_event_type_map', 'validate_event_type_string', 'validate_event_type_string_with_raise']
最新发布
09-18
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值