DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

Related

  • Decoding Database Speed: Essential Server Resources and Their Impact
  • Understanding Time Series Databases
  • Exploring Data Redaction Enhancements in Oracle Database 23ai
  • The Rise of the Intelligent AI Agent: Revolutionizing Database Management With Agentic DBA

Trending

  • Serverless Machine Learning: Running AI Models Without Managing Infrastructure
  • Deploying LLMs Across Hybrid Cloud-Fog Topologies Using Progressive Model Pruning
  • Microservice Madness: Debunking Myths and Exposing Pitfalls
  • Scaling Multi-Tenant Go Apps: Choosing the Right Database Partitioning Approach
  1. DZone
  2. Data Engineering
  3. Databases
  4. Enum Tricks: Dynamic Enums

Enum Tricks: Dynamic Enums

By 
Alexander Radzin user avatar
Alexander Radzin
·
Oct. 19, 10 · Interview
Likes (5)
Comment
Save
Tweet
Share
218.5K Views

Join the DZone community and get the full member experience.

Join For Free

Introduced to Java 1.5, Enum is a very useful and well known feature. There are a lot of tutorials that explain enums usage in details (e.g. the official Sun’s tutorial). Java enums by definition are immutable and must be defined in code. In this article I would like to explain use case when dynamic enums are needed and how to implement them.

Motivation

 There are 3 ways to use enums:

  1. direct access using the enum value, e.g. Color.RED
  2. access using enum name, e.g. Color.valueOf("RED")
  3. get enumeration of all enum values using values() method, e.g. Color.values()

Sometimes it is very convenient to store some information about enum in DB, file etc. In this case the enum defined in code must contain appropriate values.
For example let’s discover the enum Color:

enum Color {RED, GREEN, BLUE;}

Let’s assume that we would like to allow user to create his custom colors. So, we have to handle the table “Color” in database. But in this case we cannot continue using enum Color: if user adds new color (e.g. YELLOW) to DB we have to modify code and add this color to enum too.

OK, we can refuse to use enum in this case. Just rename enum to class and initialize list of colors from DB. But what if we already have 100 thousand lines of code where methods values() and valueOf() of enum Color are used? No problem: we can implement valueOf() and values() manually for the new class “Color.”

Now we see the problem. What if we have to refactor 12 enums like Color? Copy/Paste the new methods to all these classes? I would like to suggest other, more generic approach.

Making enums dynamic

Enum is compile time feature. When we create enum Foo, class Foo that extends java.lang.Enum is generated for us automatically. This is the reason that enum cannot extend other class (multiple inheritance is not supported in Java). Moreover some compiler magic prevents any attempt to manually write a class that extends java.lang.Enum.

The only solution is to write yet another class similar to Enum. I wrote class DynaEnum. This class mimics functionality of Enum but it is regular class, so it can be inherited. A static hash table holds elements of all created dynamic enums.

My DynaEnum contains a generic implementation of valueOf() and values() done using reflection, so users of this class do not have to implement them.

This class allows relatively easy refactoring for use case described above. Just change enum to class, inherit it from DynaEnum and write code to initialize members.

Example

Source code of the examples can be found here.

I implemented two examples: DigitsDynaEnum that does not have any added value relative to enum. It is implemented mostly to check that the base class functionality works. DigitsDynaEnumTest contains several unit tests.

package com.alexr.dynaenum;

public class DigitsDynaEnum extends DynaEnum<DigitsDynaEnum> {
public final static DigitsDynaEnum ZERO = new DigitsDynaEnum("ZERO", 0);
public final static DigitsDynaEnum ONE = new DigitsDynaEnum("ONE", 1);
public final static DigitsDynaEnum TWO = new DigitsDynaEnum("TWO", 2);
public final static DigitsDynaEnum THREE = new DigitsDynaEnum("THREE", 3);


protected DigitsDynaEnum(String name, int ordinal) {
super(name, ordinal);
}

    public static <E> DynaEnum<? extends DynaEnum<?>>[] values() {
    return values(DigitsDynaEnum.class);
    }

}

PropertiesDynaEnum is a dynamic enum that reads its members from properties file. Its subclass, WritersDynaEnum, reads a list of famous writers from a properties file WritersDynaEnum.properties.

package com.alexr.dynaenum;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;


public class PropertiesDynaEnum extends DynaEnum<PropertiesDynaEnum> {
protected PropertiesDynaEnum(String name, int ordinal) {
super(name, ordinal);
}

    public static <E> DynaEnum<? extends DynaEnum<?>>[] values() {
    return values(PropertiesDynaEnum.class);
    }

    protected static <E> void init(Class<E> clazz) {
    try {
initProps(clazz);
}
catch (Exception e) {
throw new IllegalStateException(e);
}
    }

    private static <E> void initProps(Class<E> clazz) throws Exception {
    String rcName = clazz.getName().replace('.', '/') + ".properties";
    BufferedReader reader = new BufferedReader(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(rcName)));

    Constructor<E> minimalConstructor = getConstructor(clazz, new Class[] {String.class, int.class});
    Constructor<E> additionalConstructor = getConstructor(clazz, new Class[] {String.class, int.class, String.class});
    int ordinal = 0;
    for (String line = reader.readLine();  line != null;  line = reader.readLine()) {
    line = line.replaceFirst("#.*", "").trim();
    if (line.equals("")) {
    continue;
    }
    String[] parts = line.split("\\s*=\\s*");
    if (parts.length == 1 || additionalConstructor == null) {
    minimalConstructor.newInstance(parts[0], ordinal);
    } else {
    additionalConstructor.newInstance(parts[0], ordinal, parts[1]);
    }
    }
    }

    @SuppressWarnings("unchecked")
private static <E> Constructor<E> getConstructor(Class<E> clazz, Class<?>[] argTypes) {
    for(Class<?> c = clazz;  c != null;  c = c.getSuperclass()) {
        try {
        return (Constructor<E>)c.getDeclaredConstructor(String.class, int.class, String.class);
        } catch(Exception e) {
        continue;
        }
    }
    return null;
    }
}

The goal is implemented! We have class that mimics functionality of enum but is absolutely dynamic. We can change list of writers without re-compiling the code. Therefore we can actually store the enum values everywhere and change “enums” at runtime.

It is not a problem to implement something like “JdbcDynaEnum” that reads values from database but this implementation is out of scope of this article.

Limitations

The solution is not ideal. It uses static initialization that could cause problems in multi-class loaders environment. Members of dynamic enums obviously cannot be accessed directly (Color.RED) but only using valueOf() or values(). But still in some cases this technique may be very useful.

Conclusions

Java enum is a very powerful feature but it has serious limitations. Enum values are static and have to be defined in code. This article suggests trick that allows to mimic enum functionality and store “enum” values separately from code.

Database

Opinions expressed by DZone contributors are their own.

Related

  • Decoding Database Speed: Essential Server Resources and Their Impact
  • Understanding Time Series Databases
  • Exploring Data Redaction Enhancements in Oracle Database 23ai
  • The Rise of the Intelligent AI Agent: Revolutionizing Database Management With Agentic DBA

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: