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.toString
The method is that all objects in Java inherit fromObject
A method of the class that returns the string representation of the object. For enum types, by default,toString
The 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 enumerationstoString
Method 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 use
enum
Keyword definition. - Each enum constant is an instance of the type.
- Fields, methods, and constructors can be defined for enumeration constants.
- Enumeration type use
-
toString
method:-
toString
The method isObject
A method of the class that returns the string representation of the object by default. - For enum types, the default
toString
Method returns the name of the enumeration constant.
-
- Custom
toString
method:- By overwriting enumeration
toString
Method, you can customize the string representation it returns. - Custom
toString
The method can return the field information of the enumeration constant.
- By overwriting enumeration
2. Code examples
Below is a complete code example that demonstrates how to customize enumerationstoString
Method 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:
- use
enum
The keyword defines a name calledPerson
The enumeration type. - Enumeration constants
ALICE
、BOB
andCHARLIE
is defined separately and specified for each constantname
、age
andjobTitle
The value of the field.
- use
- Enumerate fields and constructors:
- Inside the enum type, three private fields are defined:
name
、age
andjobTitle
。 - Define a private constructor
Person(String name, int age, String jobTitle)
, used to initialize these fields.
- Inside the enum type, three private fields are defined:
- How to get field values:
- Three public methods are defined
getName()
、getAge()
andgetJobTitle()
, used to obtainname
、age
andjobTitle
The value of the field.
- Three public methods are defined
- Coverage
toString
method:- Covered
Object
ClassictoString
Method, return a containingname
、age
andjobTitle
String representation of field values. - Use string templates (
simplified form) to format the returned string to make it easier to read.
- Covered
- Main class and method:
- Define an enumeration type inside
main
Method, used to test enumerationtoString
method. - use
for-each
Loop traversalPerson
Enumerate all constants and print their string representations.
- Define an enumeration type inside
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 itname
、age
andjobTitle
The value of the field, which is precisely by overwritingtoString
Method implemented.
V. Practical application and reference value
Custom enumerationtoString
Methods 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 enumstoString
Method 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 enumstoString
Method 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 covertoString
Method 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:
- use
enum
The keyword defines a name calledDay
enumeration type. - Enumeration constants
MONDAY
、TUESDAY
etc. are defined separately and specified for each constantdayName
anddayNumber
The value of the field.
- use
-
Enumerate fields and constructors:
- Inside the enum type, two private fields are defined:
dayName
anddayNumber
。 - Define a private constructor
Day(String dayName, int dayNumber)
, used to initialize these fields.
- Inside the enum type, two private fields are defined:
-
How to get field values:
- Two public methods are defined
getDayName()
andgetDayNumber()
, used to obtaindayName
anddayNumber
The value of the field.
- Two public methods are defined
-
cover
toString
method:- Covered
Object
ClassictoString
method, return a containingdayName
anddayNumber
A string representation of the field value. - Use string templates (
) to format the returned string to make it easier to read.
- Covered
-
Main class and method:
- Define an enumeration type inside
main
Method for testing enumerationtoString
method. - use
for-each
Loop traversalDay
Enumerate all constants and print their string representations.
- Define an enumeration type inside
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 itsdayName
anddayNumber
The value of the field, which is exactly by overwritingtoString
Method implemented.
4. Practical application and reference value
Custom enumerationtoString
Methods 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 enumstoString
Method 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!