首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring框架Java

Spring框架Java
EN

Stack Overflow用户
提问于 2021-10-21 09:31:34
回答 1查看 75关注 0票数 0
代码语言:javascript
复制
public GetChannelAccountRes getAccounts(GetChannelAccountReq request) {
        LawAccountEntity account = new LawAccountEntity();
        if(request.getTransactionCode().equals("yyyyyyy") && "1".equals(account.getAccountOwnerType())) {
           UserParameter userParameter = userParameterRepository.findByGroupKeyAndKey("xxxxxxx","11111111");
           
           
            }  
        return remoteChannelAccountInquiryService.getAccounts(request);
    }

嗨,我有这个代码块。如何在request中添加此userParameter值。我想在if语句中同时返回userParameter值和remoteChannelAccountInquiryService.getAccounts(request)值。

EN

回答 1

Stack Overflow用户

发布于 2021-10-21 13:30:16

Java作为一种语言,不允许多个返回类型,即从同一个方法返回两个值。如果你想/必须从同一个方法返回多个东西,你需要改变你的返回类型。最简单的方法是返回一个Map,即

代码语言:javascript
复制
public Map<GetChannelAccountRes,UserParameter>getAccounts(GetChannelAccountReq request) {
    Map<GetChannelAccountRes,UserParameter> map = new HashMap<>();
    if (your condition) {
      map.put(account, userParameter);
    } else {
      map.put(account, null);  // or some other default value for userParameter
    }
    return map;
}

但是调用者要么必须迭代映射键/值,要么必须知道键(即帐户)

老实说,使用Java语言的更好的解决方案是在返回UserParameter的方法中执行if语句逻辑,然后将UserParameter作为可选参数添加到现有方法中,以便始终只返回一个对象。

代码语言:javascript
复制
public UserParameter getUserParameter(GetChannelAccountReq request) {
  UserParameter userParameter = null;  // or some other default value
  if(request.getTransactionCode().equals("yyyyyyy") && 
    userParameter = "1".equals(account.getAccountOwnerType())) {
      userParameterRepository.findByGroupKeyAndKey("xxxxxxx","11111111");
    }  
  return userParameter;
}

public GetChannelAccountRes getAccounts(GetChannelAccountReq request, UserParameter... userParameter) {
    if (userParameter[0] != null) {
      // whatever logic that requires both request and userParameter goes here
    }
    return getChannelAccountRes
  }

如果同一个调用方同时调用getUserParameter和getAccount,那么它将同时拥有这两个对象,这就是您所说的希望同时返回这两个对象时的意图。varargs (...)getAccounts中的参数是一个风格问题,它是一个数组,这就是为什么我们要检查第一个索引是否为空。不使用var args也可以做同样的事情,如下所示。

代码语言:javascript
复制
public GetChannelAccountRes getAccounts(GetChannelAccountReq request) {
  return getAccounts(request, null); // or some default value for UserParameter intstead of null
}
public GetChannelAccountRes getAccounts(GetChannelAccountReq request, UserParameter... userParameter) { 
    if (userParameter != null) {
      // whatever logic that requires both request and userParameter goes here
    }
    return getChannelAccountRes
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69659416

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档