Java枚举-自定义名称 [英] Java enum - custom names

查看:155
本文介绍了Java枚举-自定义名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个Java枚举,其值是整数。



例如:

 公共枚举TaskStatus {
TaskCreated(1),
TaskDeleted(2)
}

但是我也想为这两个常量定义名称,例如

已创建任务和已删除任务(其中有空格)。

我想尽可能优雅地完成此操作,而无需编写

太多的额外代码。



我可以在没有附加映射的情况下实现此功能吗?

将枚举常量映射到其自定义名称?



我在此项目中使用的是JDK 6。

解决方案

为此添加一个字段:

 公共枚举TaskStatus {
TaskCreated(1,创建任务),
TaskDeleted(2,已删除任务);

私人最终int值;
private final字符串描述;

private TaskStatus(int value,String description){
this.value = value;
this.description =说明;
}

//吸气剂等

//考虑覆盖toString以返回描述
}

如果您不想指定字符串,而只想在每个大写字母前添加一个空格,那也是可行的-但就我个人而言, d坚持上述方法以简化和灵活。 (它将描述与标识符分开。)



当然,如果要使用i18n,则应该只将枚举值名称用作资源文件中的键。 / p>

I want to have a Java enum whose values are integers.

For example:

public enum TaskStatus {
    TaskCreated(1), 
    TaskDeleted(2)    
}

But I also want custom names for these two constants like
e.g. "Task Created" and "Task Deleted" (with spaces there).
I want to do it as elegantly as possible without writing
too much additional code.

Can I achieve this without an additional map which
maps the enum constants to their custom names?

I am using JDK 6 in this project.

解决方案

Just add a field for that:

public enum TaskStatus {
    TaskCreated(1, "Task Created"), 
    TaskDeleted(2, "Task Deleted");

    private final int value;
    private final String description;

    private TaskStatus(int value, String description) {
        this.value = value;
        this.description = description;
    }

    // Getters etc

    // Consider overriding toString to return the description
}

If you don't want to specify the string, and just want to add a space before each capital letter, that's feasible as well - but personally I'd stick with the above approach for simplicity and flexibility. (It separates the description from the identifier.)

Of course if you want i18n, you should probably just use the enum value name as a key into a resource file.

这篇关于Java枚举-自定义名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆