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

A New JEP to Enhance Java Enums [Code Snippet]

DZone's Guide to

A New JEP to Enhance Java Enums [Code Snippet]

Enums a versatile and useful, but they currently don't support generics. One JEP has proposed fixing that, providing even greater use for enums.

· Java Zone
Free Resource

Are you joining the containers revolution? Start leveraging container management using Platform9's ultimate guide to Kubernetes deployment.

Enum is one of the strongest features in Java. They are used as a list of constraints. An enum can contain a constructor, a method, a field etc. This link goes into some more details, but we're going to cover one important aspect of them here. 

They don't support generics.

Let's check the following code:

public enum Cars {
    AUDI(new Audi()),
    ACURA(new Acura());

    private Vehicle vehicle;

    Cars(Vehicle vehicle) {
        this.vehicle = vehicle;
    }
    public Vehicle getVehicle() {
        return vehicle;
    }
}

public abstract class Vehicle {
}

public class Acura extends Vehicle {
    public int getSerialNo() {
        return 134;
    }
}

public class Audi extends Vehicle{
    public String getName() {
        return "Audio";
    }
}


We have two different methods in the two classes. Now we can access the enum using the following:

public class Main {
    public static void main(String[] args) {
        Vehicle vehicle = Cars.ACURA.getVehicle();
    }
}


But there is no way we can call the getSerialNo() method from this.

To solve this problem, a new JEP (JDK Enhancement Proposal) has submitted.

With this JEP, we will able to do following:

public enum Cars<T extends Vehicle> {
    AUDI<Audi>(new Audi()),
    ACURA<Acura>(new Acura());

    private T vehicle;

    Cars(T vehicle) {
        this.vehicle = vehicle;
    }

    public T getVehicle() {
        return vehicle;
    }
}


And, definitely, we will able to call the getSerialNo() method like following:

Cars.ACURA.getVehicle().getSerialNo();


Moving towards a private or Hybrid cloud infrastructure model? Get started with our OpenStack Deployment Models guide to learn the proper deployment model for your organization.

Topics:
java ,enum ,jep ,Java generics

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 }}