I want to copy superclass object getters to subclass object setters. But how can I do this easily. I’m looking for something like clone. Could you please me help me to find it?
A simple code:
Super class:
public class SuperClass1 {
private String name;
private String surname;
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getSurname() {
return this.surname;
}
}
Subclass:
public class SubClass1 extends SuperClass1 {
private float gpa;
public void setGpa(float gpa) {
this.gpa = gpa;
}
public float getGpa() {
return gpa;
}
}
And caller class:
public class CallerClass1 {
public static void main(String[] args) {
SuperClass1 super1 = new SuperClass1();
SubClass1 subclass1 = new SubClass1();
// How to subclass1 object values easily taken from super1
}
}
If performance is not an issue here, you can copy all the properties from one class to the other making use of reflection.
Check this link to this other question that explains how to do it:
Copy all values from fields in one class to another through reflection
This other link will give you the code, without using BeanUtils:
http://blog.lexique-du-net.com/index.php?post/2010/04/08/Simple-properties-Mapper-by-reflection
I always make use of this kind of functions in my projects. Really usefull.