考虑 A 类
class A {
int i;
int j;
int k;
}
这是 B 类
class B {
int a;
int b;
int c;
}
我想知道java是否有任何这样的功能,允许编写/定义我们自己的自定义转换逻辑。
例如 将 B 类的对象转换为 A 类的对象,其中
i -> a // i pointing to value of a
j -> b // j pointing to value of b
k -> c // k pointing to value of c
(我可以根据自己的意愿自定义逻辑)
我有一些重量级对象要“转换”到其他一些类中使用,但我不想为此编写转换器方法。
(转换仅对所考虑的对象进行操作,不会创建另一个对象)
对此有什么想法/建议吗?
感谢期待!
最佳答案
您可以使用 ModelMapper
( documentation ) 等框架来定义映射逻辑,并使用它将对象从一种类型转换为另一种类型的对象。例如。配置如下:
//Model Classes
class A{
int a;
}
class B{
int d;
}
//Mappings
PropertyMap<A, B> map = new PropertyMap<A, B>() {
protected void configure() {
map(source.a, destination.d);
}
};
//Test Program
public static void main(String[] args) throws Exception {
ModelMapper mapper = new ModelMapper();
PropertyMap<A, B> map = new PropertyMap<A, B>() {
protected void configure() {
map(source.a, destination.d);
}
};
mapper.addMappings(map);
A a = new A();
a.a = 10;
B b = mapper.map(a, B.class);
System.out.println(b.d);
}
关于java - 在java中将一个类转换为另一个非层次类形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41789829/