I’m using reflection to map getters from one class to setters in another i.e. I have form classes used by stuts1 for display mostly text (Strings) and I have pure Java objects used by the back end which holds the values in their specific type. I’ve currently got the mapping working between the getters and setters which was easy but I’m having trouble with the mixed types. I’m using the parameter type from the setter to see what’s expected and so I need to determine the type of the object from the getter and cast it some how to the expected type.
E.g.
HomePageForm -> HomePageData
Name="Alexei" -> String name; (Maps correctly)
Age="22" -> int age; (Needs casting from string to int and visa-vera in reverse)
The following is my code so far
/**
* Map the two given objects by reflecting the methods from the mapTo object and finding its setter methods. Then
* find the corresponding getter method in the mapFrom class and invoke them to obtain each attribute value.
* Finally invoke the setter method for the mapTo class to set the attribute value.
*
* @param mapFrom The object to map attribute values from
* @param mapTo The object to map attribute values to
*/
private void map(Object mapFrom, Object mapTo) {
Method [] methods = mapTo.getClass().getMethods();
for (Method methodTo : methods) {
if (isSetter(methodTo)) {
try {
//The attribute to map to setter from getter
String attName = methodTo.getName().substring(3);
//Find the corresponding getter method to retrieve the attribute value from
Method methodFrom = mapFrom.getClass().getMethod("get" + attName, new Class<?>[0]);
//If the methodFrom is a valid getter, set the attValue
if (isGetter(methodFrom)) {
//Invoke the getter to get the attribute to set
Object attValue = methodFrom.invoke(mapFrom, new Object[0]);
Class<?> fromType = attValue.getClass();
//Need to cast/parse type here
if (fromType != methodTo.getParameterTypes()[0]){
//!!Do something to case/parse type!!
} //if
//Invoke the setter to set the attribute value
methodTo.invoke(mapTo, attValue);
} //if
} catch (Exception e) {
Logger.getLogger(Constants.APP_LOGGER).fine("Exception in DataFormMappingService.map: "
+ "IllegalArgumentException" + e.getMessage());
continue;
}
} //if
} //for
} //map
Thanks in advance,
Alexei Blue.
I implemented a better solution in the end:
It’s cleaner than my original solution but essentially when mapping, a filter is built of methods to map which is simply looped through and then mapped. The parse method just checks types and uses the valueOf method on an Object.toString() which works for standard Java types.
Cheers,
Alexei Blue.