方便地在 enum 和 int/String 之间映射 [英] Conveniently map between enum and int / String

查看:24
本文介绍了方便地在 enum 和 int/String 之间映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

处理只能取有限数量值的变量/参数时,我尝试始终使用 Java 的 enum,如

When working with variables/parameters that can only take a finite number of values, I try to always use Java's enum, as in

public enum BonusType {
  MONTHLY, YEARLY, ONE_OFF
}

只要我留在我的代码中,就可以正常工作.但是,我经常需要与其他使用纯 int(或 String)值用于相同目的的代码交互,或者我需要从/向数据库读取/写入数据存储为数字或字符串的地方.

As long as I stay inside my code, that works fine. However, I often need to interface with other code that uses plain int (or String) values for the same purpose, or I need to read/write from/to a database where the data is stored as a number or string.

在那种情况下,我想有一种方便的方法将每个枚举值与一个整数相关联,这样我就可以双向转换(换句话说,我需要一个可逆枚举").

In that case, I'd like to have a convenient way to associate each enum value with a an integer, such that I can convert both ways (in other words, I need a "reversible enum").

从 enum 到 int 很容易:

Going from enum to int is easy:

public enum BonusType {
  public final int id;

  BonusType(int id) {
    this.id = id;
  }
  MONTHLY(1), YEARLY(2), ONE_OFF(3);
}

然后我可以访问 int 值作为 BonusType x = MONTHLY;int id = x.id;.

Then I can access the int value as BonusType x = MONTHLY; int id = x.id;.

然而,我看不出有什么好的方法可以反过来,即从 int 到 enum.理想情况下,类似

However, I can see no nice way for the reverse, i.e. going from int to enum. Ideally, something like

BonusType bt = BonusType.getById(2); 

我能想到的唯一解决方案是:

The only solutions I could come up with are:

  • 将查找方法放入枚举,该方法使用 BonusType.values() 填充映射int -> enum",然后将其缓存并将其用于查找.会工作,但我必须将此方法完全相同地复制到我使用的每个枚举中:-(.
  • 将查找方法放入静态实用程序类中.然后我只需要一个查找"方法,但我必须摆弄反射才能使其适用于任意枚举.
  • Put a lookup method into the enum, which uses BonusType.values() to fill a map "int -> enum", then caches that and uses it for lookups. Would work, but I'd have to copy this method identically into each enum I use :-(.
  • Put the lookup method into a static utility class. Then I'd only need one "lookup" method, but I'd have to fiddle with reflection to get it to work for an arbitrary enum.

对于这样一个简单的 (?) 问题,这两种方法似乎都非常笨拙.

Both methods seem terribly awkward for such a simple (?) problem.

还有其他想法/见解吗?

Any other ideas/insights?

推荐答案

http://www.javaspecialists.co.za/archive/Issue113.html

该解决方案与您的解决方案类似,将 int 值作为枚举定义的一部分.然后他继续创建一个基于泛型的查找实用程序:

The solution starts out similar to yours with an int value as part of the enum definition. He then goes on to create a generics-based lookup utility:

public class ReverseEnumMap<V extends Enum<V> & EnumConverter> {
    private Map<Byte, V> map = new HashMap<Byte, V>();
    public ReverseEnumMap(Class<V> valueType) {
        for (V v : valueType.getEnumConstants()) {
            map.put(v.convert(), v);
        }
    }

    public V get(byte num) {
        return map.get(num);
    }
}

这个解决方案很好,不需要摆弄反射",因为它基于这样一个事实,即所有枚举类型都隐式继承了 Enum 接口.

This solution is nice and doesn't require 'fiddling with reflection' because it's based on the fact that all enum types implicitly inherit the Enum interface.

这篇关于方便地在 enum 和 int/String 之间映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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