This is not a simple solution, but you may try to... patch the Java compiler.
When you write an enum
, the Java compiler generate a class which extends java.lang.Enum
(possibly several classes, if there are constant-specific methods). The class has some (hidden) static fields, which, at the bytecode level, are initialized with the special <clinit>()
method (which the JVM calls when the class is first used). As any other method, the code for the <clinit>()
method is limited to 65535 bytes. Each constant contributes to about 20 to 22 bytes in the <clinit>()
bytecode (more if there are constant-specific constructors), so you hit the limit at about 3000 enumeration constants.
Now the <clinit>()
method has a funny name but it is nothing really special; it can invoke other methods. The Java compiler could split the mammoth <clinit>()
into several hidden sub-methods which <clinit>()
would then invoke one after the other. The Java compiler does not currently do that, but it theoretically could. The result would be processable by any JRE.
Alternatively, synthesize your enum class synthetically, generating bytecode from a dedicated program, possibly itself written in Java. In essence, this is like writing your own specialized compiler, for a specific target and using your own source syntax. The BCEL library may help.
Note that there are other limits which could jump on you. For each enumeration constant, the static code (the one in <clinit>()
) uses two "constants", which are internal values aggregated in the "constant pool" part of the compiled class. The two values are the constant name (as a string) and the resulting static field reference. There is a hard limit on 65536 constant pool entries (indexes are on 16 bits), so no more than a bit more than 32000 enumeration constants. A patched Java compiler could walk around that limit by generating several hidden classes, each with its own constant pool. A harder limit is in the number of static fields: each enumeration constant becomes a static field in the "enum" class, and there can be no more than 65535 fields (static or not) in a class.