SoFunction
Updated on 2025-04-14

Java custom enum toString method to display its field information

In Java programming, an enum is a special data type that defines a fixed set of constants. Enumeration types are not limited to simple constant definitions, but can also include fields, methods, and constructors, making them more expressive.toStringThe method is that all objects in Java inherit fromObjectA method of the class that returns the string representation of the object. For enum types, by default,toStringThe method returns the name of the enumeration constant. However, in practical applications, we may want the returned string to contain more information, such as the field values ​​of enumerated constants. This article will discuss in detail how to customize enumerationstoStringMethod to show its field information and provide a complete and straightforward code example.

Example 1

1. Theoretical Overview

  • The basic structure of enumeration:
    • Enumeration type useenumKeyword definition.
    • Each enum constant is an instance of the type.
    • Fields, methods, and constructors can be defined for enumeration constants.
  • toStringmethod:
    • toStringThe method isObjectA method of the class that returns the string representation of the object by default.
    • For enum types, the defaulttoStringMethod returns the name of the enumeration constant.
  • CustomtoStringmethod:
    • By overwriting enumerationtoStringMethod, you can customize the string representation it returns.
    • CustomtoStringThe method can return the field information of the enumeration constant.

2. Code examples

Below is a complete code example that demonstrates how to customize enumerationstoStringMethod to display its field information.

// Define an enumeration type containing fieldspublic enum Person {
    // Define enumeration constants and specify field values ​​for each constant    ALICE("Alice", 30, "Engineer"),
    BOB("Bob", 25, "Designer"),
    CHARLIE("Charlie", 35, "Manager");
 
    // Enumerate fields    private String name;
    private int age;
    private String jobTitle;
 
    // Enumeration constructor, used to initialize fields    Person(String name, int age, String jobTitle) {
         = name;
         = age;
         = jobTitle;
    }
 
    // Method to get the name    public String getName() {
        return name;
    }
 
    // How to get age    public int getAge() {
        return age;
    }
 
    // How to get a job    public String getJobTitle() {
        return jobTitle;
    }
 
    // Override the `toString` method to return a string representation containing field information    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", jobTitle='" + jobTitle + '\'' +
                '}';
    }
 
    // Main class, `toString` method used to test enumeration    public static void main(String[] args) {
        // Iterate through the enum constants and print their string representations        for (Person person : ()) {
            (person);
        }
    }
}

3. Code analysis

  • Define the enum type:
    • useenumThe keyword defines a name calledPersonThe enumeration type.
    • Enumeration constantsALICEBOBandCHARLIEis defined separately and specified for each constantnameageandjobTitleThe value of the field.
  • Enumerate fields and constructors:
    • Inside the enum type, three private fields are defined:nameageandjobTitle
    • Define a private constructorPerson(String name, int age, String jobTitle), used to initialize these fields.
  • How to get field values:
    • Three public methods are definedgetName()getAge()andgetJobTitle(), used to obtainnameageandjobTitleThe value of the field.
  • CoveragetoStringmethod:
    • CoveredObjectClassictoStringMethod, return a containingnameageandjobTitleString representation of field values.
    • Use string templates (simplified form) to format the returned string to make it easier to read.
  • Main class and method:
    • Define an enumeration type insidemainMethod, used to test enumerationtoStringmethod.
    • usefor-eachLoop traversalPersonEnumerate all constants and print their string representations.

4. Operation results

When running the above code, the following results are output:

Person{name='Alice', age=30, jobTitle='Engineer'}
Person{name='Bob', age=25, jobTitle='Designer'}
Person{name='Charlie', age=35, jobTitle='Manager'}

The string representation of each enumeration constant contains itnameageandjobTitleThe value of the field, which is precisely by overwritingtoStringMethod implemented.

V. Practical application and reference value

Custom enumerationtoStringMethods to show their field information have a wide range of uses in practical applications:

  • Logging: Record details of enumeration constants in the log, which helps in debugging and tracking.
  • user interface: Display detailed information of enumeration constants on the user interface to improve the user experience.
  • Data exchange: Include detailed information of enumeration constants in data exchange formats (such as JSON, XML), enhancing the readability and integrity of the data.

Through the detailed discussion and code examples of this article, readers can learn how to customize enumstoStringMethod to display its field information and flexibly use this technique in actual projects. This not only improves the readability and maintainability of the code, but also enhances the functionality and user experience of the application.

Example 2

1. Code examples

Below is a detailed code example showing how to customize enumstoStringMethod to contain its field information. This example defines an enumeration type that represents the weekDay, and provide a name and corresponding numeric representation for each enum constant. Then, we will covertoStringMethod to return a string containing this information.

// Define an enumeration type containing fields Daypublic enum Day {
    // Define enumeration constants and specify field values ​​for each constant    MONDAY("Monday", 1),
    TUESDAY("Tuesday", 2),
    WEDNESDAY("Wednesday", 3),
    THURSDAY("Thursday", 4),
    FRIDAY("Friday", 5),
    SATURDAY("Saturday", 6),
    SUNDAY("Sunday", 7);
 
    // Enumerate fields    private String dayName;
    private int dayNumber;
 
    // Enumeration constructor, used to initialize fields    Day(String dayName, int dayNumber) {
         = dayName;
         = dayNumber;
    }
 
    // Method to get the name    public String getDayName() {
        return dayName;
    }
 
    // How to get numbers    public int getDayNumber() {
        return dayNumber;
    }
 
    // Override the `toString` method to return a string representation containing field information    @Override
    public String toString() {
        return "Day{" +
                "dayName='" + dayName + '\'' +
                ", dayNumber=" + dayNumber +
                '}';
    }
 
    // Main class, `toString` method used to test enumeration    public static void main(String[] args) {
        // Iterate through the enum constants and print their string representations        for (Day day : ()) {
            (day);
        }
    }
}

2. Code analysis

  • Define the enum type:

    • useenumThe keyword defines a name calledDayenumeration type.
    • Enumeration constantsMONDAYTUESDAYetc. are defined separately and specified for each constantdayNameanddayNumberThe value of the field.
  • Enumerate fields and constructors:

    • Inside the enum type, two private fields are defined:dayNameanddayNumber
    • Define a private constructorDay(String dayName, int dayNumber), used to initialize these fields.
  • How to get field values:

    • Two public methods are definedgetDayName()andgetDayNumber(), used to obtaindayNameanddayNumberThe value of the field.
  • covertoStringmethod:

    • CoveredObjectClassictoStringmethod, return a containingdayNameanddayNumberA string representation of the field value.
    • Use string templates () to format the returned string to make it easier to read.
  • Main class and method:

    • Define an enumeration type insidemainMethod for testing enumerationtoStringmethod.
    • usefor-eachLoop traversalDayEnumerate all constants and print their string representations.

3. Operation results

When running the above code, the following results are output:

Day{dayName='Monday', dayNumber=1}
Day{dayName='Tuesday', dayNumber=2}
Day{dayName='Wednesday', dayNumber=3}
Day{dayName='Thursday', dayNumber=4}
Day{dayName='Friday', dayNumber=5}
Day{dayName='Saturday', dayNumber=6}
Day{dayName='Sunday', dayNumber=7}

The string representation of each enumeration constant contains itsdayNameanddayNumberThe value of the field, which is exactly by overwritingtoStringMethod implemented.

4. Practical application and reference value

Custom enumerationtoStringMethods to show their field information have a wide range of uses in practical applications. For example, in logging, including details of enum constants can help debug and track. On the user interface, displaying details of enumeration constants can improve the user experience. In addition, including detailed information about enumeration constants in data exchange formats (such as JSON, XML), can enhance the readability and integrity of the data.

Through this article's detailed discussion and code examples, readers can learn how to customize enumstoStringMethod to display its field information and flexibly apply this technique in real projects. This not only improves the readability and maintainability of the code, but also enhances the functionality and user experience of the application.

The above is the toString method of Java custom enum to display its field information in detail. For more information about Java custom toString method, please pay attention to my other related articles!