杰瑞科技汇

Java中enum和String如何转换?

Of course! This is a very common and important concept in Java. Let's break down what an enum is, how it works with strings, and the best practices for using them.

Java中enum和String如何转换?-图1
(图片来源网络,侵删)

What is an Enum?

An enum (short for enumeration) is a special data type in Java that represents a fixed set of constants. It's a special kind of class that can only have a predefined list of instances (the enum constants).

Think of it like a set of named, unique values. For example, days of the week, planets in the solar system, or card suits are all perfect candidates for enums.

Basic Syntax

public enum Day {
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
}

Key points:

  • public enum Day declares a new enum type named Day.
  • MONDAY, TUESDAY, etc., are the public, static, final instances of the Day class. You don't use new to create them.
  • By default, each constant is assigned an integer value: MONDAY is 0, TUESDAY is 1, and so on.

How to Get a String from an Enum

There are two primary ways to get a string representation of an enum constant.

Java中enum和String如何转换?-图2
(图片来源网络,侵删)

Method 1: toString() (The Standard Way)

Every enum has a toString() method that returns the name of the constant as a String. This is the most common and recommended way.

public class Main {
    public static void main(String[] args) {
        Day today = Day.FRIDAY;
        // Using toString() is implicit here
        String dayString = today.toString();
        System.out.println("Today is: " + dayString); // Output: Today is: FRIDAY
        System.out.println("Direct print: " + today);   // Output: Direct print: FRIDAY
    }
}
enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

Why is this the best way?

  • Readability: myEnum.toString() is clear and universally understood.
  • Consistency: It's the standard method defined by the Enum class.

Method 2: name() (Less Common)

The name() method also returns the name of the enum constant as a String. For most simple enums, name() and toString() produce the same result.

However, you can override toString() to provide a more user-friendly string, while name() will always return the original identifier.

Java中enum和String如何转换?-图3
(图片来源网络,侵删)
public class Main {
    public static void main(String[] args) {
        Day today = Day.FRIDAY;
        System.out.println("Using name(): " + today.name()); // Output: Using name(): FRIDAY
        System.out.println("Using toString(): " + today.toString()); // Output: Using toString(): Friday (see enum below)
    }
}
enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
    // Overriding toString() to provide a more readable format
    @Override
    public String toString() {
        return this.name().charAt(0) + this.name().substring(1).toLowerCase();
    }
}

In this example, today.name() still returns "FRIDAY", but today.toString() returns the more user-friendly "Friday".


How to Get an Enum from a String

This is a very common requirement, for example, when you read a value from a configuration file or a user input.

Method 1: valueOf(String name) (The Standard Way)

The valueOf(String) static method is built into the Enum class. It takes a string and returns the corresponding enum constant.

Crucial: The string must exactly match the name of an enum constant (case-sensitive).

public class Main {
    public static void main(String[] args) {
        String dayName = "WEDNESDAY";
        try {
            // Convert string to enum
            Day day = Day.valueOf(dayName);
            System.out.println("Converted enum: " + day); // Output: Converted enum: WEDNESDAY
        } catch (IllegalArgumentException e) {
            System.out.println("Error: No enum constant with name '" + dayName + "'");
        }
    }
}
enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

Important: If you pass a string that doesn't match (e.g., "wednesday" or "NotADay"), valueOf() will throw an IllegalArgumentException. You should always wrap it in a try-catch block or validate the string first.

Method 2: A Safer, Case-Insensitive Approach

Using valueOf() can be brittle because of case sensitivity. A more robust approach is to iterate through the enum values and compare them case-insensitively.

public class Main {
    public static void main(String[] args) {
        String dayInput = "friday"; // Lowercase input
        // A safer way to convert string to enum
        Day day = fromString(dayInput);
        if (day != null) {
            System.out.println("Successfully converted to: " + day); // Output: Successfully converted to: FRIDAY
        } else {
            System.out.println("Invalid day name: " + dayInput);
        }
    }
    /**
     * Safely converts a string to an enum value, ignoring case.
     * @param name The string to convert.
     * @return The corresponding enum constant, or null if not found.
     */
    public static Day fromString(String name) {
        for (Day day : Day.values()) {
            if (day.name().equalsIgnoreCase(name)) {
                return day;
            }
        }
        return null; // Or throw an exception
    }
}
enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

This fromString method is much more forgiving for user input.


Advanced: Enums with Custom Fields and Methods

Enums are not just simple constants; they are full-fledged classes. You can add fields, constructors, and methods to make them more powerful.

This is extremely useful for associating data with each enum constant.

Example: A Status enum with a description and a method.

public enum Status {
    // Each constant can have its own data
    PENDING("Order is being processed"),
    PROCESSING("Order is being shipped"),
    SHIPPED("Order is on its way"),
    DELIVERED("Order has been delivered"),
    CANCELLED("Order was cancelled");
    // A field to hold the description
    private final String description;
    // A private constructor to initialize the fields
    // This is automatically called for each constant
    Status(String description) {
        this.description = description;
    }
    // A public getter method to access the description
    public String getDescription() {
        return description;
    }
}
// --- How to use it ---
public class Main {
    public static void main(String[] args) {
        Status myOrderStatus = Status.PROCESSING;
        System.out.println("Status: " + myOrderStatus); // Uses toString()
        System.out.println("Description: " + myOrderStatus.getDescription()); // Output: Description: Order is being shipped
        // You can also add behavior
        if (myOrderStatus.isDelivered()) {
            System.out.println("This order is complete!");
        }
    }
}
// (To make the isDelivered method work, add it to the Status enum)
// Add this inside the Status enum:
// public boolean isDelivered() {
//     return this == DELIVERED;
// }

Summary: Best Practices

Task Recommended Method Why?
Get a string from an enum myEnum.toString() It's the standard, readable way. You can customize it by overriding the method.
Get the raw identifier string myEnum.name() Use this only if you are sure you need the exact, original identifier and not a user-friendly string.
Convert a string to an enum EnumType.valueOf("EXACT_NAME") Fast and standard, but throws an exception if the string doesn't match exactly. Use with caution.
Convert a string to an enum (safe) Iterate through EnumType.values() and compare Much safer for user input or data from external sources. Allows for case-insensitive comparison.
Associate data with an enum Add fields, a constructor, and getter methods This is the power of enums! It makes your code type-safe, readable, and encapsulates related data.
分享:
扫描分享到社交APP
上一篇
下一篇