Enumerations are pretty handy when it comes to define your own schema for static fields and we all know the power of enumerations so I'm not going to discuss more about enumerations here as you would find many blogs and articles on it.
Today, we are going to discuss the use case where we will need to use enumerations to provide dynamic validations on input fields using reflection and also will see bit more complex example where will need to use reflection to invoke enumeration itself.
Problem Statement:
Suppose you are receiving the input as CSV file and need to validate all the input fields based on below criteria:
- Field should be validated based on max length.
- Field should be validated based on access types: mandatory or optional.
- Field should be validated based on data type: alphanumeric, numeric (decimal), date etc.
Now, in order to satisfy above requirements, obvious way one would think of is to put if else blocks on each input fields and validate all of above criteria.
Well, nothing wrong with that but it's a old fashioned or rather cruel way of doing things. Java provides many robust features after 1.5 version onwards and we should leverage it.
So, closely observing above requirements you can see we need two static schemas at first: Data type & Access type which can be defined as given below.
public enum DataTypes {
ALPHANUMERIC, NUMERIC, DATE, STRING;
}
public enum AccessTypes {
OPTIONAL, CONDITIONAL, MANDATORY;
}
Now using above schema, we want to define the CSV schema for the field validations.
public enum CSVFieldEnumerations {
ESCROW_ACCOUNT(0, "escrowAccount", "Escrow Account", DataTypes.ALPHANUMERIC, 12 , 0, AccessTypes.MANDATORY),
CURRENCY(1, "currency", "Currency", DataTypes.ALPHANUMERIC, 3, 0, AccessTypes.MANDATORY),
PRINCIPAL(2, "principal", "Principal", DataTypes.NUMERIC, 17, 2, AccessTypes.MANDATORY),
START_DATE(3, "startDate", "Start Date", DataTypes.ALPHANUMERIC, 8, 0, AccessTypes.MANDATORY);
private int columnNumber;
private String columnName;
private String columnDescription;
private DataTypes columnType;
private int maxLength;
private int decimalPlaces;
private AccessTypes accessType;
private CSVFieldEnumerations(int columnNumber,
String columnName,
String columnDescription,
DataTypes columnType,
int maxLength,
int decimalPlaces,
AccessTypes accessType) {
this.columnNumber = columnNumber;
this.columnName = columnName;
this.columnDescription = columnDescription;
this.columnType = columnType;
this.maxLength = maxLength;
this.decimalPlaces = decimalPlaces;
this.accessType = accessType;
}
}
Suppose we are using the CSVParser class to read the CSV and validate all input values.JDK provides special Set & Map interfaces to iterate through the enums: EnumSet & EnumMap. We will be using EnumSet here to iterate over the enumerations defined here.
for (CSVFieldEnumerations schema: EnumSet.allOf(CSVFieldEnumerations.class)) {
Now, lets see how we can utilize the schema to provide the dynamic validations. We will create static methods to access these dynamic properties and provide validations.
public final static String validateAlphaNumericField(CSVFieldEnumerations column, String value) {
if(StringValidation.checkLength(value, column.getMaxLength())) {
if(!StringValidation.isAlphanumeric(column.getColumnName())) {
return column.getColumnDescription() + " is not an alphanumeric value";
} else {
return null;
}
} else {
return "Mandatory field " + column.getColumnDescription() + " exceeds size " + column.getMaxLength();
}
}
As you can see here, we are accessing the schema values using the enumerations to do validations here.
So we have used the schema to do dynamic validations but we also want to create CSVRecord object from the raw input data and our enumeration will do that as well for us. Remember we have defined columnName in our schema which will be the field name of CSVRecord object.
Reflection:
Field field = CSVRecord.class.getDeclaredField(schema.getColumnName());
setterMethod = CSVRecord.class.getMethod("set" + StringUtils.capitalize(schema.getColumnName()), (Class) field.getType());
setterMethod.invoke(result, currentColumn.trim());
So here we will iterate through the EnumSet for each enumeration constants defined in the schema and will validate based on the metadata defined along with setting up the CSVRecord Object.
So two birds with single stone !!
This is the power of Enumeration when combined with Reflection.
Reflection to load Enumerations:
Now, let's make above example bit more complex and consider the scenario where you need one more layer to load enumerations itself using the reflection.
Say, you have 4 different CSVs to parse and prepare common CSVRecord to send out as XML. so one will say what's the big deal, I'll set the CSV type in the parser and then will use that to load enumeration and then iterate it over using EnumSet like we did above.
Well, here is the catch, while you fetch the enumeration using EnumSet.allOf(), you need to cast it to perticular enumeration but here you don't have any type to cast unless you do it in if else blocks for each enumeration defined for the CSV type because Enumerations cannot subclassed and so you dont' have supertype here.
Well, alternately you can use generics to load enumerations using the reflection as given here.
Class enumClass = Class.forName("com.csv." + this.csvTypes);
Object[] enumConstants = enumClass.getEnumConstants();
for (int i = 0; i < enumConstants.length; i++) {
Class sub = enumConstants[0].getClass();
enumColumnName = sub.getDeclaredMethod("getColumnName");
columnNameValue = String.valueOf(enumColumnName.invoke(enumConstants[i]));
.
.
.
.
So, here we are using '?' since we don't know the type of the returned enumeration but still able to invoke the getters on the enum properties to achieve the desired results !!
Hope, this will help you understand enumerations and refection concepts.
so happy reading......
No comments:
Post a Comment