Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Extended Enums usage

DZone's Guide to

Extended Enums usage

· Java Zone
Free Resource

Learn how our document data model can map directly to how you program your app, and native database features like secondary indexes, geospatial and text search give you full access to your data. Brought to you in partnership with MongoDB.

Since the re-launch of extended enums I'm paying attention in my everyday coding (yes I still write code :) if extended enums will help me.
Here are 2 new examples:

1) I found out that most of the time the name() of the enum is not what I need. I need it to map an XML or HTML tag, an external ID, an entry name in excel or simple type name in a JSON object. So I write something like:

    public enum ConfigName {
        ALL("local-all"),
        INTERNAL("local-int"),
        OR("local-int-ext");

        private final String xmlKey;

        LdapConfig(String xmlKey) {
            this.xmlKey = xmlKey;
        }

        public String getXmlKey() {
            return xmlKey;
        }
    }

I could remove the getter, and the IDE helping a lot writing the boiler plate code but why? Here is how it should look:

    public enum ConfigName extends AlternateEnumKey {
        ALL("local-all"),
        INTERNAL("local-int"),
        OR("local-int-ext");
    }

The extra feature here is that the name() of the enum (ALL, INTERNAL, OR) is a constant that is not recognized as such by the javac compiler. So:

    @XmlTag(tag = ConfigName.ALL)

will not compile and so:

    @XmlTag(tag = ConfigName.ALL.xmlKey)

will for sure not.

But with extended enum you'll have:

    public @interface XmlTag { AlternateEnumKey tag(); }

    // The framework managing XmlTag will take the alternate key value
    @XmlTag(tag = ConfigName.ALL)

2) Since extended enums also supports generics for enums, and I just have this issue associating also a long (ID) to an enums, you can now write:

    public enum ConfigName extends EnumPairExtension<Long, String> {
        ALL(45L, "local-all"),
        INTERNAL(56L, "local-int"),
        OR(98L, "local-int-ext");
    }

    assert ConfigName.OR.a == 98L;

With this, parsing definitions are a lot cleaner to write.

From http://freddy33.blogspot.com/2011/07/extended-enums-usage.html

Discover when your data grows or your application performance demands increase, MongoDB Atlas allows you to scale out your deployment with an automated sharding process that ensures zero application downtime. Brought to you in partnership with MongoDB.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}