最近在使用一个内部框架的时候,希望能够在运行时指定枚举类型,却发现这是一件挺麻烦的事情(不找别的替代方式,就是要动态增加 enum 的类型),方法也不正统,不过作为有趣的尝试,研究研究也无妨,下面的内容主要来自于 《Java – create enum instances dynamically》这样一篇文章。在一切开始前,如果你想问,为什么非要增加/改变 enum 类型?其实这是一个非常好的问题,多数情况下这是应对被避免的,但是这不在今天我的讨论范围内。
一、方法 void addEnum(Class enumType, String enumName),用于增加一个枚举类型:
/**
* Add an enum instance to the enum class given as argument
*
* @param the type of the enum (implicit)
* @param enumType the class of the enum to be modified
* @param enumName the name of the new enum instance to be added to the class.
*/
@SuppressWarnings("unchecked")
public static > void addEnum(Class enumType, String enumName) {
// 0. Sanity checks
if (!Enum.class.isAssignableFrom(enumType)) {
throw new RuntimeException("class " + enumType + " is not an instance of Enum");
}
// 1. Lookup "$VALUES" holder in enum class and get previous enum instances