代码之家  ›  专栏  ›  技术社区  ›  Matthew Gaiser

在Java中,如何基于参数返回两种不同的类型?

  •  1
  • Matthew Gaiser  · 技术社区  · 6 年前

    public AbstractContractApplication acceptOffer(AcceptedOfferDto dto)
    {
        // various application stuff
        Contract contract; // deeply integrated into the above code
        return processedApplication;  // also deeply integrated into the above code 
    }
    

    我想重构我的方法以有时返回 contract 而不是 processedApplication 基于 AcceptedOfferDto . 理想情况下是这样的:

    if (AcceptedOfferDto.getReturnConfig() == 1){
    return contract;
    }
    
    else {
    return processedApplication; 
    }
    

    有没有一种干净的方法可以做到这一点,不需要在函数中复制和粘贴大量代码,也不需要重构一大块极其重要的业务逻辑?

    当前的思路是创建一个包含两个对象实例的类,并从中选择正确的值。还有其他的选择吗?

    3 回复  |  直到 6 年前
        1
  •  2
  •   Victor Stafusa - BozoNaCadeia Sankar    6 年前

    假设 Contract 和 AbstractContractApplication

    public interface EitherOne<A, B> {
        public default boolean isA() { return false; }
        public default boolean isB() { return false; }
        public default A getA() { throw new IllegalStateException(); }
        public default B getB() { throw new IllegalStateException(); }
    
        public static <A, B> EitherOne<A, B> a(A a) {
            return new EitherOne<>() {
                @Override public boolean isA() { return true; }
                @Override public boolean getA() { return a; }
            };
        }
    
        public static <A, B> EitherOne<A, B> b(B b) {
            return new EitherOne<>() {
                @Override public boolean isB() { return true; }
                @Override public boolean getB() { return b; }
            };
        }
    }
    

    我真的不建议任何人用这个。它应该只作为一个快速和肮脏的逃生舱门黑客复杂的情况下使用。

    然后,您可以尝试:

    public EitherOne<Contract, AbstractContractApplication> acceptOffer(AcceptedOfferDto dto) {
        // various application stuff
        AbstractContractApplication processedApplication = ...;
        Contract contract = ...; // deeply integrated into the above code
        if (AcceptedOfferDto.getReturnConfig() == 1) return EitherOne.a(contract);
        return EitherOne.b(processedApplication);  // also deeply integrated into the above code 
    }
    
        2
  •  -1
  •   Glenn Sandoval    6 年前

    类型 contract (合同)和 processedApplication AbstractContractApplication .

        3
  •  -1
  •   juuso    6 年前

    processedApplication 和 contract 是 AbstractContractApplication . 在这种情况下,函数的输出是 抽象合同应用 你不可能知道输出是不是 处理应用程序 合同 没有演员。但其中一个强制转换将失败,因此您必须处理类强制转换异常。