Today we’ll talk about working with string enumerations, and more specifically, with
enum
classes that organize interaction with string constants.
Using String Enumerations
During application development, you periodically need to operate on a fixed set of string values. It could be anything. For example, a list of color codes supported by the application, or a list of devices with which our application can interact, seasons, etc. All this is a predefined set of string constants with a common structure, with which it is necessary to establish program interaction at the Java code level. When you need to interact with a predefined set of string (and other) constants, the best solution is to write your ownenum
class. Below we will look at examples of conversion enum
to string
.
Creating String Enumerations
Let's createenum
a class that stores a list of different environments for deploying the application, as well as the URL of each environment:
public enum Environment {
PROD("https://release.application.com/"),
TEST("https://test.application.com/"),
AUTO_TEST("https://autotest.application.com/"),
DEV("http://localhost:8080");
private final String url;
Environment(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
}
In this class we have defined 4 environments:
PROD
- releaseTEST
— for manual testingAUTO_TEST
— environment for autotestsDEV
— local for development and debugging
- Each URL is a string constant in our enumeration: they are defined in parentheses next to each
enum
constant. - There must be a constructor that takes an argument of the same type as each
enum
constant. - The scope of the constructor is
private
eitherpackage private
. - It is necessary to define a variable - a class field that will store the string constants we have defined. You must create a getter method for this field in order to use the values of string constants externally.
Iterating over string enumerations
At this stage, we can already iterate over all availableenum
values, as well as get string constants associated with them. To get all the values of any enum
class, you need to use the method values()
:
public class Main {
public static void main(String[] args) {
for (Environment env : Environment.values()) {
System.out.println(env + " : " + env.getUrl());
}
}
}
Conclusion:
PROD : https://release.application.com/
TEST : https://test.application.com/
AUTO_TEST : https://autotest.application.com/
DEV : http://localhost:8080
As can be seen from the example, to print the name of enum
the constant, we passed it to the method System.out.println
, and to print the url associated with this constant, we used the getter we defined.
Getting a string constant from enum
To get the value of any string constant, we can also call a getter on anyenum
constant:
public class Main {
public static void main(String[] args) {
String prodUrl = Environment.PROD.getUrl();
String devUrl = Environment.DEV.getUrl();
System.out.println("Production url is: " + prodUrl);
System.out.println("Development url is: " + devUrl);
}
}
Conclusion:
Production url is: https://release.application.com/
Development url is: http://localhost:8080
Getting enum constant by name
Sometimes it is necessary to getenum
a constant by its string name. This is done using the method valueOf(String)
, which returns a constant by its name:
public class Main {
public static void main(String[] args) {
Environment prod = Environment.valueOf("PROD");
Environment dev = Environment.valueOf("DEV");
System.out.println("Production url is: " + prod.getUrl());
System.out.println("Development url is: " + dev.getUrl());
}
}
Conclusion:
Production url is: https://release.application.com/
Development url is: http://localhost:8080
But caution is needed here. If the method does not find enum
a constant with the specified name, an exception will be thrown java.lang.IllegalArgumentException
.
Converting String to Enum
Sometimes the opposite need arises. Knowing the valueenum
, get enum
the constant itself. Those. in our example, knowing a certain address, you need to get the corresponding Environment
constant. There are several options to do this. And all of them require improvement in enum
the class itself. Option 1. Enumeration inside the class. You need to create a method that will accept a string and compare it with all the values enum
of the class. If there is a match, the method will return the desired enumeration. For our example, we need to Environment
create the following method inside the class:
public static Environment getEnvByUrl(String url) {
for (Environment env : values()) {
// либо equalsIgnoreCase, на ваше усмотрение
if (env.getUrl().equals(url)) {
return env;
}
}
// Либо просто вернуть null
throw new IllegalArgumentException("No enum found with url: [" + url + "]");
}
Then we can get enum
from the string like this:
public class Main {
public static void main(String[] args) {
String url = "http://localhost:8080";
Environment env = Environment.getEnvByUrl(url);
System.out.println("Environment name for url=[" + url + "] is: " + env);
}
}
Conclusion:
Environment name for url=[http://localhost:8080] is: DEV
This approach has its downsides. Each time, to obtain enum
a constant, you will have to iterate through all the values and make a certain number of comparisons. The performance penalty in this case will be determined by the number of constants and the number of similar operations. The second method of solving this problem does not have this problem. Full Enum
class code:
public enum Environment {
PROD("https://release.application.com/"),
TEST("https://test.application.com/"),
AUTO_TEST("https://autotest.application.com/"),
DEV("http://localhost:8080");
private final String url;
Environment(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
public static Environment getEnvByUrl(String url) {
for (Environment env : values()) {
if (env.getUrl().equals(url)) {
return env;
}
}
throw new IllegalArgumentException("No enum found with url: [" + url + "]");
}
}
Option 2: Usage HashMap
In this case, we create a map inside our enum and populate it once at compile time, and then take the values from it:
public enum Environment {
PROD("https://release.application.com/"),
TEST("https://test.application.com/"),
AUTO_TEST("https://autotest.application.com/"),
DEV("http://localhost:8080");
private final String url;
Environment(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
// Создаем static final карту
private static final Map<String, Environment> LOOKUP_MAP = new HashMap<>();
// Заполняем её всеми значениями
static {
for (Environment env : values()) {
LOOKUP_MAP.put(env.getUrl(), env);
}
}
// Возвращаем Environment по строковому url
public static Environment getEnvByUrl(String url) {
return LOOKUP_MAP.get(url);
}
}
In terms of use, both options are identical:
public class Main {
public static void main(String[] args) {
String url = "http://localhost:8080";
Environment env = Environment.getEnvByUrl(url);
System.out.println("Environment name for url=[" + url + "] is: " + env);
}
}
Conclusion:
Environment name for url=[http://localhost:8080] is: DEV
But this method also has disadvantages. Firstly, there is much more code. And secondly, HashMap
all enum
values will be stored in the application memory permanently. As you can see, everything has pros and cons. But considering that enum
classes usually store not so many values, the disadvantages will be almost invisible. There is a caveat: if such an operation (getting a Java Enum by String value) is performed frequently, it is better to use the second option. You can learn more about this topic and Enum
classes in general in the JavaRush course. Students learn JavaRush Enum
already at the first lecture of the fifth level .
GO TO FULL VERSION