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)值。
发布于 2021-10-21 13:30:16
Java作为一种语言,不允许多个返回类型,即从同一个方法返回两个值。如果你想/必须从同一个方法返回多个东西,你需要改变你的返回类型。最简单的方法是返回一个Map,即
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作为可选参数添加到现有方法中,以便始终只返回一个对象。
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也可以做同样的事情,如下所示。
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 getChannelAccountReshttps://stackoverflow.com/questions/69659416
复制相似问题