Not actually a one-liner but this approach doesn't require any libs.
I was testing it using these classes:
private class A {
public int x;
public String y;
@Override
public String toString() {
return "A [x=" + x + ", y=" + y + "]";
}
}
private class B {
private int x;
private String y;
public int getX() {
return x;
}
public void setX(int x) {
System.out.println("setX");
this.x = x;
}
public String getY() {
return y;
}
public void setY(String y) {
System.out.println("setY");
this.y = y;
}
@Override
public String toString() {
return "B [x=" + x + ", y=" + y + "]";
}
}
To get public field we can use reflection, as for setters it's better to use bean utils:
public static <X, Y> void copyPublicFields(X donor, Y recipient) throws Exception {
for (Field field : donor.getClass().getFields()) {
for (PropertyDescriptor descriptor : Introspector.getBeanInfo(recipient.getClass()).getPropertyDescriptors()) {
if (field.getName().equals(descriptor.getName())) {
descriptor.getWriteMethod().invoke(recipient, field.get(donor));
break;
}
}
}
}
The test:
final A a = new A();
a.x = 5;
a.y = "10";
System.out.println(a);
final B b = new B();
copyPublicFields(a, b);
System.out.println(b);
And its output is:
A [x=5, y=10]
setX
setY
B [x=5, y=10]