Java Reference
In-Depth Information
valueOf(String) method returns the enum constant whose name
exactly matches (including case) the value of the String argument, or
throws an IllegalArgumentException if there is no enum con-
stant with the specified name.
Refer to the online Java documentation for further details on java.lang.Enum
and each of its methods ( http://download.java.net/jdk8/docs/api/
java/lang/Enum.html ) . As the next recipe demonstrates, enum types, as full-
fledged Java classes, can be used to build more intelligent constants.
7-2. Designing Intelligent Constants
Problem
You need a type that can represent a fixed set of related constants, and you would like
to build some state and behavior (logic) around your constants in an object-oriented
fashion.
Solution
Use an enum type and take advantage of the fact that enum types are full-fledged Java
classes. An enum type can have state and behavior just like any other class, and the
enum constants, themselves being instances of the enum type, inherit this state and be-
havior. This is best illustrated by an example. Let's expand on the example from the
previous recipe. Imagine that you need to process and validate all the fields from an
HTML form that has been submitted. Each form field has a unique set of rules for val-
idating its content, based on the field type. For each form field, you have the field's
“name” and the value that was entered into that form field. The FieldType enum can
be expanded to handle this very easily:
// See FieldType.java
public enum FieldType {
PASSWORD("password") {
// A password must contain one or more digits,
Search WWH ::




Custom Search