钻石运算符扩展一个或另一个[重复]

问题描述 投票:0回答:1

在我的代码中,我有两个非常相似(但仍然不同)的类,但我想将它们都映射到第三个类。我是这样的:

class AToCMapper {

    public C from(A a) {
        // My mapping code
    }
}
class BToCMapper {

    public C from(B b) {
        // Same mapping code
    }
}

A 和 B 略有不同,但映射到 C 的代码是相同的。为了避免重复,我想要这样的东西:

class CMapper {

    public <T extends A | B> from (T t) {
        // My mapping code
    }
}

有办法吗?或者我被重复的代码困住了?

java generics code-duplication diamond-problem diamond-operator
1个回答
3
投票

尝试定义

MappableToC
A
都实现的
B
接口。

例如:

interface MappableToC {
  String getLabel();
  Number getData();
}

class A implements MappableToC {
  String name;
  int value;

  public String getLabel() {
    return name;
  }

  public Number getData() {
    return value;
  }
}

class B implements MappableToC {
  String title;
  double amount;

  public String getLabel() {
    return title;
  }

  public Number getData() {
    return amount;
  }
}

class C {
  String label;
  Number data;
}

class CMapper {
  public C map(MappableToC source) {
    C target = new C();
    target.label = source.getLabel();
    target.data = source.getData();
    return target;
  }
}

public class Main {
  public static void main(String[] args) {
    CMapper mapper = new CMapper();

    A aInstance = new A();
    aInstance.name = "Example A";
    aInstance.value = 42;
    C cFromA = mapper.map(aInstance);
    System.out.println(cFromA.label);
    System.out.println(cFromA.data);

    B bInstance = new B();
    bInstance.title = "Sample B";
    bInstance.amount = 3.14;
    C cFromB = mapper.map(bInstance);
    System.out.println(cFromB.label);
    System.out.println(cFromB.data);
  }
}

输出:

Example A
42
Sample B
3.14

尝试godbolt.org

© www.soinside.com 2019 - 2024. All rights reserved.