java - 在java中将一个类转换为另一个非层次类形式

标签 java casting

考虑 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/

相关文章:

java - c#模型抽象和泛型,像Java一样强制转换未知泛型

java - 尝试播放音频 (.wav) 文件时没有声音

java - 使用未指定的索引

java - 在 Spring + mysql 中使用 ACID 属性进行批量更新

c++ - 设置二维矩阵时避免段错误

c++ - 未处理的异常 - C++ 程序在转换时停止

scala - 如何避免在具有家族多态性的 Scala 中调用 asInstanceOf

快速使用 AnyClass 对象与 as?

c++ - 强制转换为派生类的 ptr 到 ptr

java - 需要有关链接列表包含方法的帮助