Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possile to cast two different class but having the same attributes?

Tags:

java

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?

like image 650
José Vilchez Almera Avatar asked Feb 11 '23 01:02

José Vilchez Almera


2 Answers

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.

like image 98
Tagir Valeev Avatar answered Feb 13 '23 05:02

Tagir Valeev


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;
}

}
like image 36
gtgaxiola Avatar answered Feb 13 '23 05:02

gtgaxiola