I have two classes. ClassA and CLassB, they don't have any relation but they both have the same attributes. Is it possible to cast them or I have to set the attributes one by one?
The only way to "cast" them universally is using the reflection like this:
public static void copyObject(Object src, Object dest)
throws IllegalArgumentException, IllegalAccessException,
NoSuchFieldException, SecurityException {
for (Field field : src.getClass().getFields()) {
dest.getClass().getField(field.getName()).set(dest, field.get(src));
}
}
Example:
static class ClassA {
public int a;
public String b;
public double c;
}
static class ClassB {
public int a;
public String b;
public double c;
}
public static void main(String[] args) throws Exception {
ClassA a = new ClassA();
a.a = 1;
a.b = "test";
a.c = 3.14;
ClassB b = new ClassB();
copyObject(a, b);
System.out.println(b.a+", "+b.b+", "+b.c); // prints "1, test, 3.14"
}
However, as you may guess, that's not very good way to do things in Java.
You can create an Interface
that gets implemented by both classes to set the attributes.
That way instead of casting you reference them by the interface
Example
public interface PersonalInfo {
public void setName(String name);
public void setAge(int age);
}
Then your implementations
public class ClassA implements PersonalInfo {
String name;
int age;
//other things and methods
@Override
public void setName(String name) {
this.name = name;
}
@Override
public void setAge(int age) {
this.age = age;
}
}
And for ClassB
public class ClassB implements PersonalInfo {
String name;
int age;
//other things and methods
@Override
public void setName(String name) {
this.name = name;
}
@Override
public void setAge(int age) {
this.age = age;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With