CiCi CiCi - 2 months ago 9
Java Question

Define Enum at Runtime using ByteBuddy

I have a project which uses an enum to be used as a parameter for a class which signature is like this:

public class MyClass<E extends Enum<E>> extends ExtendedClass

The thing is, I don't want to define an enum and do the same programming again for each new enum..

I was thinking of ByteBuddy to generate enums at runtime.. but I'm not finding a neat way to do this and the resources are not so much ..

Any help regarding this issue would be awesome!


Enum types compiled to class with static fields so

enum MyEnum {

is compiled to

class MyEnum extends java.lang.Enum<MyEnum> {
  public static final Sample FOO;
  // synthetic
  private static final Sample[] $VALUES;

  static {
    FOO = new MyEnum("FOO", 0);
    $VALUES = new MyEnum[] {FOO};

  private MyEnum(String name, int ordinal) {
    super(name, ordianl);

  // and other helpers
  public static MyEnum[] values() { /* $VALUES */ }
  public static MyEnump[] valueOf(String name) { /* $VALUES lookup */ }

(that's why enum cannot extend another class only implement interfaces). So you need to generate this kind of class to emulate enum.