使用数据库中的值填充枚举 [英] Populate an enum with values from database

查看:103
本文介绍了使用数据库中的值填充枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个映射String-> Integer的表。



我想用数据库中的值填充enum,而不是静态创建枚举。这是可能的吗?



所以,而不是分离静态:

  public enum Size {SMALL(0),MEDIUM(1),LARGE(2),SUPERSIZE(3)}; 

我想动态创建这个枚举,因为数字{0,1,2,3}基本上是随机的(因为它们是由数据库的AUTOINCREMENT列自动生成的)。 解决方案

枚举总是在编译时固定的。你可以做到这一点的唯一方法是dyamically生成相关的字节码。



话虽如此,你应该计算出你实际上感兴趣的枚举的哪些方面大概你不想在它们上面使用 switch 语句,因为这意味着静态代码,并且你不能静态地知道这些值...同样任何其他的如果你真的只想要一个从 String 整数的映射,那么Integer ,您可以使用在执行时填充的 Map< String,Integer> ,然后就完成了。如果你想获得 EnumSet 特性,它们在重现效率上会有些复杂,但是可能需要付出一些努力。

因此,在进一步思考实施之前,我建议你研究一下你的真实需求。

(编辑:我们一直假设这个枚举是完全动态的,也就是说你不知道名字或者有多少值。如果这个名字是固定的,并且你只需要 来获取ID数据库,这是一个非常不同的问题 - 请参阅安德烈亚斯的答案。)


I have a table which maps String->Integer.

Rather than create an enum statically, I want to populate the enum with values from a database. Is this possible ?

So, rather than delcaring this statically:

public enum Size { SMALL(0), MEDIUM(1), LARGE(2), SUPERSIZE(3) };

I want to create this enum dynamically since the numbers {0,1,2,3} are basically random (because they are autogenerated by the database's AUTOINCREMENT column).

解决方案

No. Enums are always fixed at compile-time. The only way you could do this would be to dyamically generate the relevant bytecode.

Having said that, you should probably work out which aspects of an enum you're actually interested in. Presumably you weren't wanting to use a switch statement over them, as that would mean static code and you don't know the values statically... likewise any other references in the code.

If you really just want a map from String to Integer, you can just use a Map<String, Integer> which you populate at execution time, and you're done. If you want the EnumSet features, they would be somewhat trickier to reproduce with the same efficiency, but it may be feasible with some effort.

So, before going any further in terms of thinking about implementation, I suggest you work out what your real requirements are.

(EDIT: I've been assuming that this enum is fully dynamic, i.e. that you don't know the names or even how many values there are. If the set of names is fixed and you only need to fetch the ID from the database, that's a very different matter - see Andreas' answer.)

这篇关于使用数据库中的值填充枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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