Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Java ENUMs with an interface?

Tags:

java

enums

I want to use an Enum in Java for storing configuration values for different environments. Each Enum will have the same fields, but different values. Something like:

public enum DevelopmentConfig
{
   URL("..."),
   defaultURL(".....");
}

public enum ProductionConfig
{
   URL("..."),
   defaultURL(".....");
}

This is for a web application, so I can't simply use Preferences or any other solution.

My question is, is there a way to create an interface to define the fields of the configuration? Or should I be using a normal class instead of enum for storing these values?

Edit: To use this, I simply want to do this from my other classes:

String url = Config.URL

Or

String url = Config.getURL();

Without knowing if that refers to Config.Development or Config.Production (I want that to be determined in the Config enum's constructor itself and have it choose the right set of fields)

like image 825
Ali Avatar asked Jun 12 '26 13:06

Ali


2 Answers

You're misusing enums.

Each enum member can be implemented as an anonymous class that overrides things:

public enum Config {
    DEVELOPMENT {
        @Override
        ...
    },
    PRODUCTION {
        @Override 
        ...
    };

    public abstract ...;
}
like image 170
SLaks Avatar answered Jun 14 '26 02:06

SLaks


You can also use enum in the following manner. With this you can store(and retrieve) different values for each Config

    public enum Config{
        DEVELOPMENT("DEV_URL", "DEV_DEFAULT_URL"), 
        PRODUCTION("PROD_URL", "PROD_DEFAULT_URL");

    private String url;

    private String defaultURL;

    Config( String url, String defaultURL )
    {
        setUrl(url);
        setDefaultURL(defaultURL);
    }

    public String getUrl()
    {
        return url;
    }

    public String getDefaultURL()
    {
        return defaultURL;
    }

    public void setDefaultURL( String defaultURL )
    {
        this.defaultURL = defaultURL;
    }

    public void setUrl( String url )
    {
        this.url = url;
    }
}
like image 36
Shiva Kumar Avatar answered Jun 14 '26 03:06

Shiva Kumar