Today we will talk about working with string enumerations, and more specifically, with
enum
classes in which interaction with string constants is organized.
Using string enums
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 is able to interact, seasons, etc. All this is a predefined set of string constants with a common structure, with which it is necessary to establish programmatic interaction at the Java code level. When it is necessary to interact with a predefined set of string (and not only) constants, the best solution is to write your ownenum
class. Below are examples of converting enum
to string
.
Creating string enums
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 of our enum: 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 defined by us. For this field, you need to create a getter method in order to use the values of string constants from outside.
Iterating over string enums
At this stage, we can already iterate through all the availableenum
values, as well as get the 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 you can see 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 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 an enum constant by name
Sometimes it is necessary to getenum
a constant by its string name. This is done using a method valueOf(String)
that 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 here caution is needed. If the method does not find enum
a constant with the specified name, an exception will be thrown java.lang.IllegalArgumentException
.
Convert String to Enum
Sometimes the need arises. Knowing the value ofenum
, 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 for doing this. And all of them require refinement in enum
the class itself. Option 1. Search inside the class. You need to create a method that will take a string and compare it with all the values enum
of the class. If it matches, the method will return the desired enum. For our example, you 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 a 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 over all the values and make a number of comparisons. The performance penalty in this case will be determined by the number of constants and the number of such operations. The second way to solve this problem does not have such a 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 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. First, the code has become much larger. And secondly, HashMap
with all enum
the values it will be stored in the application memory permanently. As you can see, everything has pros and cons. But given that enum
not so many values are usually stored in classes, the disadvantages will be almost imperceptible. There is a nuance: if such an operation (getting a Java Enum by String value) is performed often, it is better to use the second option. You can learn more about this topic and Enum
classes in general on the CodeGym course. CodeGym students study Enum
already at the first lecture of the fifth level .