How can I extend an existing enum in Java to add new elements?

One more dynamic way I’ve handled the java extend enum issue is by combining multiple enums in a wrapper class. This method works great when you don’t need to modify the enums directly but still want to merge them. I’ve used a Set to store values from both enums dynamically, like this:

import java.util.EnumSet;
import java.util.Set;

enum A { a, b, c }
enum B { d, e }

public class EnumCombiner {
    public static Set<Enum<?>> combinedEnum = EnumSet.noneOf(A.class);
    
    static {
        combinedEnum.addAll(EnumSet.allOf(A.class));
        combinedEnum.addAll(EnumSet.allOf(B.class));
    }

    public static void main(String[] args) {
        System.out.println(combinedEnum); // Output: [a, b, c, d, e]
    }
}

Why is this useful? This approach gives you the ability to combine enums dynamically without needing to modify the original enum types. It also allows you to work with them as a unified collection, which is pretty flexible when you’re dealing with evolving sets of values. It’s a workaround for the java extend enum restriction that can be very useful in certain situations.