【问题标题】:Passing null to methods with Optional as parameters [closed]将 null 传递给使用 Optional 作为参数的方法[关闭]
【发布时间】:2022-01-03 19:17:29
【问题描述】:
CONTROLLER CLASS
@PostMapping("Calculate")
    public String Calculate(@ModelAttribute("currencyAndAmount") @Valid CurrencyViewModel currencyViewModel,
                            BindingResult bindingResult, Model model) {
        if (!bindingResult.hasErrors()) {
            var entity = currencyExchange_logic.CurrencyViewModelToEntity(currencyViewModel);
            String start = Optional.ofNullable(entity.getDateFrom().toString()).orElse("");
            String end = Optional.ofNullable(entity.getDateTo().toString()).orElse("");
            try {
                var currencyJson = currencyExchange_logic.currencyJson(start, end);
                var calVal = currencyExchange_logic.calculateMoney(currencyJson, entity);
                model.addAttribute("endValue", calVal);
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
            return "end";
        } else {
            return "formPage";
        }
    }

SERVICE CLASS

@Override
    public MonetaryAmountJson currencyJson(String start, String end) throws IOException {
        String dates = "/" + start + "/" + end;
        URL url = new URL("http://api.nbp.pl/api/exchangerates/tables/c" + dates);
        URLConnection urlConnection = url.openConnection();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        StringBuilder jsonObject = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            jsonObject.append(line);
        }
        bufferedReader.close();
        Gson gson = new Gson();
        return gson.fromJson(String.valueOf(jsonObject), MonetaryAmountJson.class);
    }

我的问题是:

var currencyJson = currencyExchange_logic.currencyJson(start, end);

所以在前端表单中有 2 个日期输入可以留空(不是由用户填写) 我想将其中的逻辑传递给 currencyJson() 方法 Optional.of(given date (maybe null).toString()) ,即 Optional.ofNullable(null).orElse("");不会返回“”(空字符串)。我是否将“”或 null 传递给 currencyJson()?

【问题讨论】:

  • 在您当前的代码Optional.ofNullable(entity.getDateFrom().toString()) 中,如果entity.getDateFrom()null,肯定会抛出NullPointerException。你应该试试Optional.ofNullable(entity.getDateFrom()).map(Date::toString).orElse("");
  • 另外请尽量不要包含与问题无关的代码。

标签: java null optional


【解决方案1】:

如果 entity.getDateFrom() 实际上是 null,Optional.ofNullable(entity.getDateFrom().toString()) 应该抛出一个 NullPointerException,因为在调用 Optional.ofNullable 之前,toString 将在 null 上调用。

但您的问题并未说明您在原始代码中得到 NullPointerException,因此请认为日期值不是为空,而是一些默认值。

现在,如果默认值实际上为 null,并且您想继续使用 Optional,则可以改为:

String start = Optional.ofNullable(entity.getDateFrom())
                       .map(Object::toString)
                       .orElse("")
String end = Optional.ofNullable(entity.getDateTo())
                       .map(Object::toString)
                       .orElse("");

...或者(更简单):

String start = Objects.toString(entity.getDateFrom(), "")
String end = Objects.toString(entity.getDateTo(), "")

【讨论】:

  • 谢谢,toString() 正在抛出 nullpointerxception
猜你喜欢
  • 2010-09-07
  • 1970-01-01
  • 2014-11-17
  • 1970-01-01
  • 2013-01-25
  • 2014-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多