Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get() methods in Java enum type

Tags:

java

enums

I have an enum type (say for arguments sake CarModel), used throughout an application (numerous classes).

public enum CarModel {
    DIABLO,
    P911,
    DB7;
}

I have various methods that use this CarModel enum type in different ways, and each has a switch statement to set some String variable depending on the enum type, before going on to do other stuff. (e.g. set the Manufacturer of some model, or set the country of origin etc. These results are static at runtime)

The issue is, if I want to add a new model to the enum, I'd need to go to each method, and extend/modify the switch statement to handle its existence. This could easily lead to human error, and/or code duplication (if various methods use the same switch statements).

Rather than using switch statements all-over, I would like to have static methods, that could be edited in a single location, and would allow for behaviour similar to the following:

String country = CarModel.DIABLO.getCountry() // returns Italy
String manufacturer = CarModel.P911.getManufacturer() // returns  Porsche

Is this possible with an enum, (and is an enum even the 'correct' way to do this?

like image 227
Jonny Avatar asked Jul 24 '12 11:07

Jonny


1 Answers

You can do something like this.

public enum CarModel {
    DIABLO("Lamborghini", "Italy"),
    P911("Porsche", "Germany");

    private String manufacturer;
    private String country;

    private CarModel(String manufacturer, String country) {
        this.manufacturer = manufacturer;
        this.country = country;
    }

    public String getManufacturer() {
        return manufacturer;
    }

    public String getCountry() {
        return country;
    }
}
like image 175
Jesper Avatar answered Sep 18 '22 23:09

Jesper