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

Build vs Buy a Data Quality Solution: Which is Best for You? Gain insights on a hybrid approach. Download white paper now!

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


Build vs Buy a Data Quality Solution: Which is Best for You? Maintaining high quality data is essential for operational efficiency, meaningful analytics and good long-term customer relationships. But, when dealing with multiple sources of data, data quality becomes complex, so you need to know when you should build a custom data quality tools effort over canned solutions. Download our whitepaper for more insights into a hybrid approach.

Topics:
java ,enum ,jep ,Java generics

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}