You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从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;
    }
}

关键说明

  1. 静态资源加载:ResourceBundle.getBundle("errorcodes")会自动加载classpath下的errorcodes.properties文件,无需手动处理IO流。
  2. 键值转换:枚举构造函数不再直接存储键,而是通过getResourceValue方法从资源文件中获取对应值,同时添加异常处理避免因键不存在导致崩溃。
  3. 资源文件位置:确保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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 00:50:38