如何投射不互相继承的对象? [英] How can I cast objects that don't inherit each other?
问题描述
我有2个不同的类,它们具有不同的字段,而一个类具有这两个类的所有字段.有什么方法可以将对象投射到两个单独的对象中?
I have 2 different classes with different fields and a class which has all the fields of both classes. Is there any way to cast the object in to two separate objects?
class A{
private int a;
private int b;
}
class B{
private int a;
private int b;
}
如果对象 D
具有A和B类的所有属性,是否有办法分别转换它们?
If object D
have all the properties of A and B classes, Is there any way to cast them separately?
推荐答案
从孩子到父母的铸造(垂头丧气),反之亦然(铸造):
Casting take place from child to parent (downcast) or vise versa (upcast):
class A extends B
B b = (B)(new A());
,或者在使用接口的情况下:
or in case of interfaces:
List<String> myList = new ArrayList<>();
ArrayList<String> myArrayList = (ArrayList)myList;
投放时要小心-如果无法投放,则会收到 Exception
!
Be careful when casting - if casting is not possible, you'll receive Exception
!
在您的情况下,映射是您要寻找的.您只需要一个映射器.
In your case, mapping is what you're looking for. You simply need a mapper.
例如:
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
}
}
这篇关于如何投射不互相继承的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!