如何投射不相互继承的对象?

YD_*_*YD_ 2 java casting object

我有两个不同的类,不同的字段和一个类,其中包含两个类的所有字段.有没有办法将对象转换为两个单独的对象?

class A{
    private int a;
    private int b;
}

class B{ 
    private int a;
    private int b;
}
Run Code Online (Sandbox Code Playgroud)

如果object D具有A和B类的所有属性,有没有办法单独转换它们?

xen*_*ros 5

从孩子到父母的投射(向下投射)或反之亦然(向上投射):

class A extends B
B b = (B)(new A());
Run Code Online (Sandbox Code Playgroud)

或者在接口的情况下:

List<String> myList = new ArrayList<>();
ArrayList<String> myArrayList = (ArrayList)myList;
Run Code Online (Sandbox Code Playgroud)

铸造时要小心 - 如果无法铸造,你会收到Exception!

在您的情况下,映射是您正在寻找的.你只需要一个映射器.

例如:

public class AToBMapper {
    public static A fromB(B b) {
        A a = new A();
        a.setA(b.getA());
        a.setB(b.getB());
        return a;
    }

    public static B fromA(A a) {
        //fill in
    }
}
Run Code Online (Sandbox Code Playgroud)