As a user requirement i have to extract data from a few different Excel files and for each of them concatenate their values (for each row, converted to strings where needed) to save the result to DB. I already have mapped those excel files to a different bean (POJO) for each of them. What i would like to do is to call every getter by reflection and , with a single method, handle all of them (and their future modifications!) without having to manually invoke each getter (easy, but error-prone and requesting a code change for every excel file modification). This is what i've got so far :
public String getConcatenatedValues(Class beanClass, Object myBean) throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{
String output = "";
for(PropertyDescriptor propertyDescriptor : Introspector.getBeanInfo(beanClass, BeanBase.class).getPropertyDescriptors()){
Method myMethod = propertyDescriptor.getReadMethod();
Object resultFromGetter = myMethod.invoke(myBean);
//missing logic here
output += resultFromGetter.toString();
}
return output;
}
BaseBean here is a class every bean extends of which i do not want to call the getters. I'm only interested in beanClass getters. What i'd need is a dynamic cast to the class returned by myMethod.getReturnType() to be able to call the toString() method of the correct class. Is this a correct approach? Is it doable by reflection alone?
Aucun commentaire:
Enregistrer un commentaire