将 null 传递给以 Optional 作为参数的方法

Passing null to methods with Optional as parameters

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("");不会 return ""(空字符串)。我是将 "" 还是 null 传递给 currencyJson()?

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

但是你的问题并没有说明你在原始代码中得到了 NullPointerException,所以认为日期值是 not 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(), "")