简体   繁体   English

使用 Map 的方法“getOrDefault()”

[英]Work with method "getOrDefault()" of the Map

I want to get flashAttribute when from one page is redirected to another page and set it to model.当从一个页面重定向到另一个页面并将其设置为模型时,我想获取 flashAttribute。 And I try to use this code:我尝试使用此代码:

Map<String, ?> map = RequestContextUtils.getInputFlashMap(request);
if (map != null) {
    // this is redirect
    model.addAttribute("attr", map.getOrDefault("attr", false));
}

I have an error:我有一个错误:

The method getOrDefault(Object, capture#3-of ?) in the type Map is not applicable for the arguments (String, boolean)类型 Map 中的 getOrDefault(Object, capture#3-of ?) 方法不适用于参数 (String, boolean)

What can I do to solve this problem with getOrDefault("attr", false) method?如何使用 getOrDefault("attr", false) 方法解决此问题?

You need to make an unchecked cast of the map:您需要对地图进行未经检查的演员表:

Map<String, Object> map =
    (Map<String, Object>) RequestContextUtils.getInputFlashMap(request);

The wildcard in the returned map type is rather wrong, it should have been Map<String, Object> .返回的地图类型中的通配符相当错误,它应该是Map<String, Object>

In both cases, get(K) returns Object , but the wildcard forbids the methods with ?在这两种情况下, get(K)返回Object ,但通配符禁止使用? type as an argument such as V in put(K, V) , which might pollute the type-correctness of the map contents.如类型作为参数Vput(K, V)这可能污染的地图内容的类型正确性。

The problem is that this also affects methods such as getOrDefault(K, V) , which do not actually modify the map.问题是这也会影响getOrDefault(K, V)等方法,这些方法实际上并不修改地图。

对于通配符值,您可以简单地将调用getOrDefault map为您想要的值类型:

    model.addAttribute("attr", ((Map<String, Boolean>) map).getOrDefault("attr", false));

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

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