Copy Properties or how to Clone a Class to a different Class
René has asked me how to copy properties/fields of an instance of one class to an instance of another class. I.e. you have
class A {
int a
}
and
class B {
int a
}
where B obviously does not extend A. You want to copy all properties of an instance of A to an instance of B.
Copy Properties
The solution is to access the properties property of A, filter it to remove the class and metaClass fields (which can’t be copied) and then use the GroovyObject#setProperty method on an instance of B.
class Copy {
static GroovyObject copy(GroovyObject from, GroovyObject to) {
from?.properties?.findAll { !(it.key =~ ~/(meta)?[cC]lass/) }?.each {
try {
to.setProperty(it.key, from[it.key])
}
catch (MissingPropertyException ex) {}
}
to
}
static <T> T copy(GroovyObject from, Class<T> to) {
copy(from, to.newInstance())
}
}
Clone a Class to a different Class
The code also lets you instantiate classes which is useful in case you want to clone an instance of A down its class hierarchy.
class A {
int a
}
class C extends A {
int foo
}
Calling
A someA = new A(a: 42)
C someC = use (Copy) { someA.copy(C) }
will give you a clone of A that is of type C.
