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

Microservices. Streaming data. Event Sourcing and CQRS. Concurrency, routing, self-healing, persistence, clustering...learn how Akka enables Java developers to do all this out of the box! Brought to you in partnership with Lightbend.

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();


Microservices. Streaming data. Event Sourcing and CQRS. Concurrency, routing, self-healing, persistence, clustering...learn how Akka enables Java developers to do all this out of the box! Brought to you in partnership with Lightbend. 

Topics:
java ,enum ,jep ,Java generics

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}