如何从properties文件键直接为Java枚举设置对应值?
解决方案:枚举加载properties值而非键的问题
问题根源
你的枚举类仅直接将构造函数传入的properties键赋值给msg和code字段,未从errorcodes.properties文件中加载对应实际值,因此返回的是键字符串而非期望内容。
修复方案
在枚举类中静态加载properties资源,并在枚举实例初始化时根据键获取对应值,具体代码如下:
修正后的ErrorCodes枚举
import java.util.MissingResourceException; import java.util.ResourceBundle; public enum ErrorCodes { ID_REQUIRED("error.id.required.message", "error.id.required.code"), ID_INVALID("error.id.invalid.message", "error.id.invalid.code"); // 静态加载classpath下的errorcodes.properties资源文件 private static final ResourceBundle ERROR_RESOURCES = ResourceBundle.getBundle("errorcodes"); private final String msg; private final String code; private ErrorCodes(String msgKey, String codeKey) { // 根据键获取对应值,找不到时返回键本身避免程序崩溃 this.msg = getResourceValue(msgKey); this.code = getResourceValue(codeKey); } private static String getResourceValue(String key) { try { return ERROR_RESOURCES.getString(key); } catch (MissingResourceException e) { return key; } } public String getMsg() { return msg; } public String getCode() { return code; } }
关键说明
- 静态资源加载:
ResourceBundle.getBundle("errorcodes")会自动加载classpath下的errorcodes.properties文件,无需手动处理IO流。 - 键值转换:枚举构造函数不再直接存储键,而是通过
getResourceValue方法从资源文件中获取对应值,同时添加异常处理避免因键不存在导致崩溃。 - 资源文件位置:确保
errorcodes.properties放在项目classpath目录下(Maven/Gradle项目通常为src/main/resources),否则ResourceBundle无法找到文件。
验证效果
执行throw new CustomException(ErrorCodes.ID_REQUIRED)时,CustomException从枚举中获取的errorMessage会是Id is required to get the details.,errorCode会是110,符合预期。
内容的提问来源于stack exchange,提问作者avarshne
相关产品推荐
相关产品推荐

