Как enum преобразовать в string java
Перейти к содержимому

Как enum преобразовать в string java

  • автор:

How to Convert a String to Enum in Java?


Java enum are powerful data types that represent a fixed set of constants. They are commonly used to outline a specific set of values that an object can take. Sometimes, you may want to convert a string illustration into an enum value. In this context, we will explore diverse strategies to convert a string to an enum in Java, offering you with a whole program for a better understanding.

Understanding Enum in Java:

Before diving into the conversion process, let’s briefly recap Java enum. Enumerations, or enum for short, were introduced in Java 5 to provide a more structured way of representing constant values. An enum declaration defines a fixed set of values that a variable of that enum type can take. Each value in an enum is called an enum constant.

Here’s an example of an enum declaration:

In this case, Day is the name of the enum, and it has seven constants representing the days of the week. Enum can also have additional fields and methods, making them more flexible and powerful than simple constant values.

Converting a String to Enum:

When you’ve got a string representation and also you want to convert it to an enum, you could follow different tactics based to your requirements. Here, we will speak 3 common methods for acting this conversion: the usage of the valueOf() method, the use of a custom mapping, and the use of the Enum.ValueOf() method.

Method 1: Using valueOf() Method

The maximum direct manner to convert a string to an enum is with the aid of the usage of the valueOf() technique furnished by means of the enum itself. This approach takes the name of the enum consistent as a string and returns the corresponding enum regular if discovered. Here’s an example:




In this example, we convert the string «FRIDAY» to the Day enum by calling the valueOf() method. The result is the Day.FRIDAY enum constant, which is then printed to the console.

It’s important to note that the valueOf() method is case-sensitive, and if the string does not match any enum constant, a java.lang.IllegalArgumentException will be thrown. To handle this, you can wrap the conversion in a try-catch block to handle the exception gracefully.

Method 2: Using a Custom Mapping

In some cases, you may need to perform a custom mapping between the string representation and the enum constant. This approach is useful when the string values don’t match the enum constant names exactly. Here’s an example:




In this example, the Day enum has an additional field called abbreviation, which represents a shorter string representation of the day. We define a custom method fromAbbreviation() that performs the conversion based on the abbreviation. If the abbreviation matches any enum constant, the corresponding enum constant is returned; otherwise, an exception is thrown.

Method 3: Using the Enum.valueOf() Method

The third method involves using the Enum.valueOf() method, which is a general-purpose method for converting strings to enum constants. Here’s an example:




In this example, we pass the enum class (Day.class) and the string representation (dayString) to the Enum.valueOf() method. It returns the corresponding enum constant if found, or throws an IllegalArgumentException if no match is found.

In this article, we explored different methods for converting a string to an enum in Java. We discussed using the valueOf() method, creating a custom mapping, and utilizing the Enum.valueOf() method. Depending on your requirements, you can choose the most appropriate approach. Remember to handle exceptions when using the valueOf() method, and consider a custom mapping when the string values don’t match the enum constant names directly.

Next Topic Illustrate Class Loading and Static Blocks in Java Inheritance


For Videos Join Our Youtube Channel: Join Now


  • Send your Feedback to [email protected]

Преобразование строки в элемент enum

Только я получаю его как String, а нужно что бы вернул типа enum PriorityType. Как выкрутиться из этой ситуации?

23.4k 3 3 золотых знака 50 50 серебряных знаков 70 70 бронзовых знаков
задан 10 апр 2015 в 6:06
duddeniska duddeniska
3,968 17 17 золотых знаков 67 67 серебряных знаков 113 113 бронзовых знаков

1 ответ 1

Сортировка: Сброс на вариант по умолчанию

Для преобразования строки в элемент enum в каждом enum’е есть метод valueOf :

PriorityType high = PriorityType.valueOf("HIGH"); 

Этот метод чувствителен к регистру, передаваемая строка должна в точности повторять имя элемента enum’а.

Ещё один вариант, позволяющий кастомизировать строки, на основании которых создаются элементы enum’а. Он строится на основе использования конструктора и реализации своего метода преобразования строки в елемент enum’а:

public enum PriorityType < LOW("LowPrioroty"), MIDDLE("MiddlePrioroty"), HIGH("HighPrioroty"); private String value; private PriorityType(String value) < this.value = value; >public static PriorityType fromString(String value) < if (value != null) < for (PriorityType pt : PriorityType.values()) < if (value.equalsIgnoreCase(pt.value)) < return pt; >> > throw new IllegalArgumentException("No such value"); > > PriorityType low = PriorityType.fromString("lowpriority"); 

Convert String to equivalent Enum value

Is it possible for me to convert a String to an equivalent value in an Enumeration , using Java. I can of course do this with a large if-else statement, but I would like to avoid this if possible. Given this documentation: http://download.oracle.com/javase/1.4.2/docs/api/java/util/Enumeration.html I am not too hopeful that this is possible without ifs or a case statement.

asked Aug 14, 2011 at 13:07
50.6k 110 110 gold badges 242 242 silver badges 316 316 bronze badges

5 Answers 5

Hope you realise, java.util.Enumeration is different from the Java 1.5 Enum types.

You can simply use YourEnum.valueOf(«String») to get the equivalent enum type.

Thus if your enum is defined as so:

public enum Day

You could do this:

String day = "SUNDAY"; Day dayEnum = Day.valueOf(day); 

answered Aug 14, 2011 at 13:10
61.9k 23 23 gold badges 139 139 silver badges 169 169 bronze badges
yes thanks just saw this download.oracle.com/javase/1,5.0/docs/api/java/lang/Enum.html
Aug 14, 2011 at 13:11

thanks @adarshr, but question. What happens if the value doesn’t belong to the group. e.g. Day.valueOf(«randomValue»);

Mar 8, 2021 at 6:29

@ArtanisZeratul — If the provided value isn’t present in the enum, you’ll get an IllegalArgumentException.

May 21, 2021 at 13:42

Assuming you use Java 5 enums (which is not so certain since you mention old Enumeration class), you can use the valueOf method of java.lang.Enum subclass:

MyEnum e = MyEnum.valueOf("ONE_OF_CONSTANTS"); 

answered Aug 14, 2011 at 13:10
22.6k 10 10 gold badges 55 55 silver badges 79 79 bronze badges

Use static method valueOf(String) defined for each enum .

For example if you have enum MyEnum you can say MyEnum.valueOf(«foo»)

answered Aug 14, 2011 at 13:10
115k 16 16 gold badges 131 131 silver badges 210 210 bronze badges

I might’ve over-engineered my own solution without realizing that Type.valueOf(«enum string») actually existed.

I guess it gives more granular control but I’m not sure it’s really necessary.

public enum Type < DEBIT, CREDIT; public static MaptypeMapping = Maps.newHashMap(); static < typeMapping.put(DEBIT.name(), DEBIT); typeMapping.put(CREDIT.name(), CREDIT); >public static Type getType(String typeName) < if (typeMapping.get(typeName) == null) < throw new RuntimeException(String.format("There is no Type mapping with name (%s)")); >return typeMapping.get(typeName); > > 

I guess you’re exchanging IllegalArgumentException for RuntimeException (or whatever exception you wish to throw) which could potentially clean up code.

answered Jun 14, 2017 at 22:56
12.4k 7 7 gold badges 64 64 silver badges 72 72 bronze badges

The other responses about using valueOf(string) are right on, but I would add that you should protect your code for the potential for an invalid string to be passed. While today your code may only pass strings that correspond with valid enum values it is possible for a future change to the enum or a future change to other parts of your code (or code written by others) to break this assumption.

This will be important for cases like when writing a setter for a class’s enum member variable. Your class and its setter should protect themselves.

The JavaDocs for Enum show that an exception could be thrown on this (IllegalArgumentException or NullPointerException. You should handle these either generically or specifically. The JavaDocs also show that this function won’t like «extraneous whitespace» . so consider using trim().

I would probably handle the exceptions generically like this:

Enum BestEnumEver // . elsewhere in your code . // How confident are you that stringVar will have an acceptable value? // How confident are you that the existing enum options will not need to change? BestEnumEver enumValue; try < // Consider using trim to eliminate extraneous whitespace enumValue = BestEnumEver.valueOf(stringVar.trim()); >catch (Exception e) < // handle the situation here. Here are a couple of ideas. // Apply null and expect the using code to detect. enumValue = null; // Have a defined private constant for a default value // assuming a default value would make more sense than null enumValue = DEFAULT_BEST_ENUM_EVER; >

But you could also handle each exceptions in some unique way.

Enum BestEnumEver // . elsewhere in your code . // How confident are you that stringVar will have an acceptable value? // How confident are you that the existing enum options will not need to change? BestEnumEver enumValue; try < // Consider using trim to eliminate extraneous whitespace enumValue = BestEnumEver.valueOf(stringVar.trim()); >catch (IllegalArgumentException e1) < // handle the situation here . >catch (NullPointerException e2) < // handle the situation here . >

How to convert Enum to String in Java with Example

There are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method. name() method of Enum returns the exact same String which is used to declare a particular Enum instance like in WeekDays Enum if we have MONDAY as one Enum instance then the name() will return String «MONDAY». This method of conversion from Enum to String is useful if the String representation of Enum is the same as its String name but if you have different String representation then you can use toString() method.

Since Enum in Java allows a programmer to override an inherited method and since Enum has access to all Object class methods, you can easily override the toString() method to provide a custom String implementation for an Enum instance which can further use to convert that Enum instance to String in Java.

Both ways of converting Enum to String have their own merit and use cases. Prefer name() method if String representation of Enum instance is its declared name and prefer toString() method if every Enum Instance has its own custom String representation.

For example, if the declared enum is RED and you want text representation as «RED» then use the name() method because both are the same, but if you want String representation as «Red» then you can use the toString() method to customize that bit.

It’s actually better to use toString() from a maintenance perspective because if any developer refactors and changes the name of Enum constant then its String representation will also change, which is not a desirable coupling and should be avoided at all costs.

Java Example to Convert Enum to String

In the following example, we will see both ways of converting Enum into String in Java. This program also demonstrates the use of the Enum.values() method which returns all Enum instances, which can be used to iterate over all enum constants.

How to convert Enum to String in Java with Example

You can just iterate or print values or do anything you would like to with those constants. In this example, you can see we have two enums Weekdays and ColdDrink, first uses the name() method for converting the Enum constant to String while the second uses the toString() method instead.

package example ;

* Java program to demonstrate how to convert Enum to String in Java. This program demonstrates
* two examples by using the name() and toString() method to get a meaningful String representation
* from an Enum instance in Java.
* @author Javin Paul
public class EnumToString <
private enum Weekdays <

private enum ColdDrink <
PEPSI ( «Pepsi» ) , COKE ( «Coca Cola» ) , SPRITE ( «Sprite» ) ;
private String brandname ;
private ColdDrink ( String brand ) <
this . brandname = brand ;

public String toString () <
return brandname ;

public static void main ( String args []) <
//Converting Enum to String by using name() method
//by default print mehtod calls toString() of enum
ColdDrink [] drinks = ColdDrink. values () ;
for ( ColdDrink drink : drinks ) <
System. out . printf ( «String to Enum example using name : %s%n» , drink. name ()) ;

//Converting Enum to String using toString() method
for ( ColdDrink drink : drinks ) <
System. out . println ( «String to enum conversion using toString() : » + drink ) ;
String to Enum example using name: PEPSI
String to Enum example using name: COKE
String to Enum example using name: SPRITE
String to enum conversion using toString () : Pepsi
String to enum conversion using toString () : Coca Cola
String to enum conversion using toString () : Sprite

That’s all on How to convert Enum into String in Java. Enum provides different ways to return meaningful String representation with utmost flexibility offered by allowing overriding toString method in Java. For most cases name() method would be enough to convert Enum to String.

  1. How to use the valueOf method of Enum (check here)
  2. How to loop over Enum constants in Java (example)
  3. Top 15 Java Enum Interview Questions with Answers (see here)
  4. Can we use Enum in Switch Statement in Java (Yes)
  5. Java tip to convert Enum to String in Java (see tip)
  6. String to Enum in Java with Example (check here)
  7. Difference between RegularEnumSet and JumboEnumSet in Java (read here)
  8. What Every Java Programmer Should know about Enum (click here)
  9. 10 points about Enum in Java (see here)
  10. Learn how to use Enum in Java with a Simple Example (check here)
  11. Can Enum have Constructor in Java (learn here)

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *