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
Please enter at least three characters to search
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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

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

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Useful System Table Queries in Relational Databases
  • Introducing Graph Concepts in Java With Eclipse JNoSQL
  • Manual Sharding in PostgreSQL: A Step-by-Step Implementation Guide
  • Why Database Migrations Take Months and How to Speed Them Up

Trending

  • Chat With Your Knowledge Base: A Hands-On Java and LangChain4j Guide
  • GitHub Copilot's New AI Coding Agent Saves Developers Time – And Requires Their Oversight
  • MCP Servers: The Technical Debt That Is Coming
  • The Future of Java and AI: Coding in 2025
  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.4K 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

  • Useful System Table Queries in Relational Databases
  • Introducing Graph Concepts in Java With Eclipse JNoSQL
  • Manual Sharding in PostgreSQL: A Step-by-Step Implementation Guide
  • Why Database Migrations Take Months and How to Speed Them Up

Partner Resources

×

Comments
Oops! Something Went Wrong

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
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!