Awesome coding

Here's a function I just wrote that basically copies one object's data to another...

private void copy(Object src, Object dest) throws Exception {
  if (src.getClass().equals(dest.getClass())){
    Method []methods = src.getClass().getMethods();
    for (int i = 0; i < methods.length; i++){
      if (methods[i].getName().startsWith("get")){
        String setname = methods[i].getName().replaceFirst("get","set");
        Method setmethod = dest.getClass().getMethod(setname, new Class[]{methods[i].getReturnType()});

        Object value = methods[i].invoke(src,new Object[]{});
        Method clone = value.getClass().getDeclaredMethod("clone",new Class[]{});
        if (clone != null && clone.isAccessible()){
          value = clone.invoke(value,new Object[]{});
        }
        setmethod.invoke(dest,new Object[]{value});
      }
    }
  }
}


It's in Java, and it imports the java.lang.reflect package. It's wicked. Obviously not the most complete function. It could be in a BeanUtils class as a public static function. I could also specify whether or not I want "clone" to be used, instead of just checking if it's implemented and using it. One last thing, if the destination class is a subclass of the source class, it should still work, because the destination is guaranteed to have the same functions as the source in that case. This, of course, assumes that the objects are "beans".

blog comments powered by Disqus