This java Program copies one bean class attributes value to other class attributes with same names and methods.
to
public static void copyBean(Object srcObject ,Object targetObj){
Method [] srcObjMethod = srcObject.getClass().getMethods() ;
Method [] targetObjMethod = targetObj.getClass().getMethods() ;
List targetObjectMethodNameList = new ArrayList();
for (int counter = 0 ; counter < targetObjMethod.length ; counter++ ){
targetObjectMethodNameList.add(targetObjMethod[counter].getName());
}
for( int counter = 0; counter < srcObjMethod.length ; counter++ ){
Method getterMethod = srcObjMethod[counter] ;
if (getterMethod.getName().startsWith("get") && ! getterMethod.getName().startsWith("getClass") ){
try {
String setterMthodName = "set"+getterMethod.getName().substring(3);
System.out.println("setter method name ["+setterMthodName+"]");
Object value = getterMethod.invoke(srcObject,null);
System.out.println( ">>"+value);
try {
if (value != null && targetObjectMethodNameList.contains(setterMthodName)){
targetObj.getClass().getMethod(setterMthodName, new Class[]{ value.getClass() } ).invoke(targetObj, value) ;
}
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}
}