繁体   English   中英

我应该更喜欢ifPresent方法而不是isPresent方法吗?

[英]Should I prefer the `ifPresent` method to the `isPresent` one?

我有使用后者的代码:

Optional<String> subject = Optional.ofNullable(claims.get().getSubject());
if (subject.isPresent()) {
  UserDetails userDetails = userDetailsService.loadUserByUsername(subject.get());
  UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails,
      null, userDetails.getAuthorities());
  authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
  logger.debug("Security - The request authenticated fine from the JWT Access token");
  return authentication;
} else {
  throw new BadCredentialsException("The authentication token " + optToken + " did not contain a subject.");
}

我正在尝试使用ifPresent方法进行重构。

我应该在函数方法调用之前先调用userDetailsService.loadUserByUsername服务吗? 如果是这样,怎么办? 如何返回类型不同于功能方法类型的对象?

我正在使用Java 12。

使用map方法转换Optional的值。 转换后,可以使用orElseThrow方法解压缩Optional ,如果为空,则抛出异常。

像这样:

return Optional.ofNullable(claims.get().getSubject())
               .map(userDetailsService::loadUserByUsername)
               .map(userDetails -> {
                   UsernamePasswordAuthenticationToken authentication = 
                       new UsernamePasswordAuthenticationToken(
                           userDetails, null, userDetails.getAuthorities());
                   authentication.setDetails(
                       new WebAuthenticationDetailsSource().buildDetails(request));
                   return authentication;
               })
               .orElseThrow(() -> new BadCredentialsException(
                  "The authentication token " + optToken + " did not contain a subject."));

但是,在您的特定情况下,根本不使用Optional可能会更简单。 您可以立即检查是否为null。

String subject = claims.get().getSubject();
if (subject == null) {
    throw new BadCredentialsException(
        "The authentication token " + optToken + " did not contain a subject.");
}

UsernamePasswordAuthenticationToken authentication = ... ;

在这种情况下,可以使用orElseThrow ,如果不存在该值,则抛出异常:

String subjectValue = subject.orElseThrow(() ->
    new BadCredentialsException("The authentication token " + optToken + " did not contain a subject."));
...

如果您真的想使用ifPresent ,则可以执行以下操作

subject.ifPresent(s -> {
     UserDetails userDetails = loadUserByUsername(s);
     ...
});

但是既然您丢了一个丢失的主题,为什么不简单地做

String subject = Optional.ofNullable(claims.get().getSubject())
        .orElseThrow(() -> new BadCredentialsException(...));
UserDetails userDetails = loadUserByUsername(subject);
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM