Java 17 Recipes


Download 3.2 Mb.
Pdf ko'rish
bet132/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   128   129   130   131   132   133   134   135   ...   245
Bog'liq
Java 17 Recipes

 How It Works
Notice that the enhanced FieldType enum defines a fieldName instance variable and a 
constructor with a fieldName string argument for initializing the instance variable. Each 
enum constant (each constant being an instance of FieldType) must be instantiated 
with a fieldName. FieldType also defines an abstract validate(String) method 
that each enum constant must implement to perform the field validation. Here, each 
FieldType’s validate() method applies a regular expression match against the field 
value and returns the Boolean result of the match. Imagine the following form input 
fields corresponding to our FieldType instances.




The value of the input field’s name attribute identifies FieldType; you used this same 
name when you instantiated each FieldType enum constant. When a form is submitted
you have access to each input field’s name and the value entered in the field. You need to 
map the field’s name to a field type and call the validate() method with the input value. 
The class variable, nameToFieldTypeMap, is declared and initialized for this purpose. 
For each FieldType enum constant, nameToFieldTypeMap stores an entry with the field 
name as the key and the field type as the value. The lookup(String) class method uses 
this map to look up the field type from the field name. The code to validate an email 
input field with an input value of john@doe.com is quite concise.
Chapter 7 Data SourCeS anD ColleCtionS


248
//
String fieldName = FieldType.emailFieldName;
String fieldValue = "john@doe.com";
boolean valid = FieldType.lookup(fieldName).validate(fieldValue);
The main() method shows an example validation for each of the FieldTypes. The 
printValid() method prints the field name, field value, and the field’s validation result.
This recipe has demonstrated a lot more potential in the enum type than the ability 
to define a set of named constants. Enum types have all the power of a normal class, plus 
additional features that allow you to create well-encapsulated and intelligent constants.

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   128   129   130   131   132   133   134   135   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling