64

It is possible to add and remove elements from an enum in Java at runtime?

For example, could I read in the labels and constructor arguments of an enum from a file?


@saua, it's just a question of whether it can be done out of interest really. I was hoping there'd be some neat way of altering the running bytecode, maybe using BCEL or something. I've also followed up with this question because I realised I wasn't totally sure when an enum should be used.

I'm pretty convinced that the right answer would be to use a collection that ensured uniqueness instead of an enum if I want to be able to alter the contents safely at runtime.

Community
  • 1
  • 1
brabster
  • 42,504
  • 27
  • 146
  • 186

7 Answers7

47

No, enums are supposed to be a complete static enumeration.

At compile time, you might want to generate your enum .java file from another source file of some sort. You could even create a .class file like this.

In some cases you might want a set of standard values but allow extension. The usual way to do this is have an interface for the interface and an enum that implements that interface for the standard values. Of course, you lose the ability to switch when you only have a reference to the interface.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
  • Would you know where can I find a good example of an enum implementing such interface? I will be interested in such functionality. – megalucio Oct 19 '17 at 15:10
  • 1
    @megalucio I think I was thinking of `java.nio.file.StandardOpenOption` http://docs.oracle.com/javase/8/docs/api/java/nio/file/StandardOpenOption.html but there's also `java.net.StandardProtocolFamily` and `javax.tools.StandardLocation`. – Tom Hawtin - tackline Oct 20 '17 at 21:54
  • Thanks very much . I will have a look into it. – megalucio Oct 23 '17 at 16:51
13

Behind the curtain, enums are POJOs with a private constructor and a bunch of public static final values of the enum's type (see here for an example). In fact, up until Java5, it was considered best-practice to build your own enumeration this way, and Java5 introduced the enum keyword as a shorthand. See the source for Enum<T> to learn more.

So it should be no problem to write your own 'TypeSafeEnum' with a public static final array of constants, that are read by the constructor or passed to it.

Also, do yourself a favor and override equals, hashCode and toString, and if possible create a values method

The question is how to use such a dynamic enumeration... you can't read the value "PI=3.14" from a file to create enum MathConstants and then go ahead and use MathConstants.PI wherever you want...

Matt Lachman
  • 4,541
  • 3
  • 30
  • 40
Yuval
  • 7,987
  • 12
  • 40
  • 54
  • Never write a public static non-empty array field - they are not constant. – Tom Hawtin - tackline Jan 25 '09 at 22:37
  • Is that true? As the instance on the end of the reference is immutable, I'm not sure how you could actually change it... is it just crossed wires over whether it's an array instance or not? – brabster Jan 26 '09 at 20:13
  • 2
    Collections and Arrays are both mutable Objects (and "Objects"). Having a "final" array just means you're not going to resize or otherwise reassign the array, but it still lets you replace values that already fit in its bounds. – Ed Brannin Sep 01 '09 at 14:57
12

I needed to do something like this (for unit testing purposes), and I came across this - the EnumBuster: http://www.javaspecialists.eu/archive/Issue161.html

It allows enum values to be added, removed and restored.

Edit: I've only just started using this, and found that there's some slight changes needed for java 1.5, which I'm currently stuck with:

  • Add array copyOf static helper methods (e.g. take these 1.6 versions: http://www.docjar.com/html/api/java/util/Arrays.java.html)
  • Change EnumBuster.undoStack to a Stack<Memento>
    • In undo(), change undoStack.poll() to undoStack.isEmpty() ? null : undoStack.pop();
  • The string VALUES_FIELD needs to be "ENUM$VALUES" for the java 1.5 enums I've tried so far
Andy
  • 3,596
  • 8
  • 34
  • 33
  • 1
    With modern versions of Java, you need to change a few things as documented in the revised article: https://www.javaspecialists.eu/archive/Issue272-Hacking-Enums-Revisited.html – blalasaadri Dec 01 '20 at 13:04
6

I faced this problem on the formative project of my young career.

The approach I took was to save the values and the names of the enumeration externally, and the end goal was to be able to write code that looked as close to a language enum as possible.

I wanted my solution to look like this:

enum HatType
{
    BASEBALL,
    BRIMLESS,
    INDIANA_JONES
}

HatType mine = HatType.BASEBALL;

// prints "BASEBALL"
System.out.println(mine.toString());

// prints true
System.out.println(mine.equals(HatType.BASEBALL));

And I ended up with something like this:

// in a file somewhere:
// 1 --> BASEBALL
// 2 --> BRIMLESS
// 3 --> INDIANA_JONES

HatDynamicEnum hats = HatEnumRepository.retrieve();

HatEnumValue mine = hats.valueOf("BASEBALL");

// prints "BASEBALL"
System.out.println(mine.toString());

// prints true
System.out.println(mine.equals(hats.valueOf("BASEBALL"));

Since my requirements were that it had to be possible to add members to the enum at run-time, I also implemented that functionality:

hats.addEnum("BATTING_PRACTICE");

HatEnumRepository.storeEnum(hats);

hats = HatEnumRepository.retrieve();

HatEnumValue justArrived = hats.valueOf("BATTING_PRACTICE");
// file now reads:
// 1 --> BASEBALL
// 2 --> BRIMLESS
// 3 --> INDIANA_JONES
// 4 --> BATTING_PRACTICE

I dubbed it the Dynamic Enumeration "pattern", and you read about the original design and its revised edition.

The difference between the two is that the revised edition was designed after I really started to grok OO and DDD. The first one I designed when I was still writing nominally procedural DDD, under time pressure no less.

moffdub
  • 5,284
  • 2
  • 35
  • 32
  • 2
    the links in your post are now protected by the author and not viewable –  Aug 06 '19 at 01:13
  • Doesn't this break best practices for Java which assumes that Enumerators are static and final? It's almost like you're using a local file as a database of constant values that must be read fresh to guarantee latest as previously read data could be stale. – wheeleruniverse Dec 02 '19 at 21:01
1

You can load a Java class from source at runtime. (Using JCI, BeanShell or JavaCompiler)

This would allow you to change the Enum values as you wish.

Note: this wouldn't change any classes which referred to these enums so this might not be very useful in reality.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

A working example in widespread use is in modded Minecraft. See EnumHelper.addEnum() methods on Github

However, note that in rare situations practical experience has shown that adding Enum members can lead to some issues with the JVM optimiser. The exact issues may vary with different JVMs. But broadly it seems the optimiser may assume that some internal fields of an Enum, specifically the size of the Enum's .values() array, will not change. See issue discussion. The recommended solution there is not to make .values() a hotspot for the optimiser. So if adding to an Enum's members at runtime, it should be done once and once only when the application is initialised, and then the result of .values() should be cached to avoid making it a hotspot.

The way the optimiser works and the way it detects hotspots is obscure and may vary between different JVMs and different builds of the JVM. If you don't want to take the risk of this type of issue in production code, then don't change Enums at runtime.

radfast
  • 538
  • 1
  • 7
  • 14
0

You could try to assign properties to the ENUM you're trying to create and statically contruct it by using a loaded properties file. Big hack, but it works :)

Eldelshell
  • 6,683
  • 7
  • 44
  • 63