peichhorn / lombok-pg

Collection of lombok extensions
http://peichhorn.github.com/lombok-pg/
Other
326 stars 44 forks source link

@Copyable #110

Open nicholas22 opened 11 years ago

nicholas22 commented 11 years ago

A nice addition to this already fantastic library is a way to do some boilerplate copying from one object's POJO properties to another. At the moment I've rolled out a very simple custom copier which uses reflection, but this is clearly something that can be made to perform much faster if done statically (at compile time).

@SneakyThrows
private static void pojoCleaner(Class<?> type, Object pojo)
{
  val props = ReflectionUtils.getProperties(type, false);
  for (val prop : props)
  {
    val setter = prop.getSetter();

    System.out.println(prop.getPropertyType());
    if (prop.getPropertyType() == String.class)
      setter.invoke(pojo, new Object[] {null});
    else if (prop.getPropertyType().isArray())
      ArrayUtils.create(prop.getPropertyType().getComponentType(), 0);
    else
      // primitive int/long/etc
      setter.invoke(pojo, 0);
  }
}

@SneakyThrows
private static void pojoCopier(Class<?> type, Object from, Object to)
{
  val props = ReflectionUtils.getProperties(type, false);
  for (val prop : props)
  {
    val getter = prop.getGetter();
    val setter = prop.getSetter();

    val value = getter.invoke(from, (Object) null);
    setter.invoke(to, value);
  }
}

A classic use-case would be when needing an object pool, or for re-usable pre-allocated data buffering techniques.

Regards, Nik

peichhorn commented 11 years ago

From what I can tell, this code is supposed to perform a shallow copy and not a deep copy. Three ideas come to mind:

  1. generate a clone() method, but I don't like that too much since you can't use final fields then.
  2. generate a copy constructor
  3. generate a copy factory method

What do you prefer?

nicholas22 commented 11 years ago

Yes the shallowness is for the first version ;) Leaning towards the factory method, for ease of subclassing etc.

nicholas22 commented 11 years ago

Another case today where boilerplate was used to clone a simple POJO. This must be a useful use-case for lots of users...